Skip to content

Instantly share code, notes, and snippets.

@lamprosg
Last active August 13, 2018 13:33
Show Gist options
  • Save lamprosg/2436540 to your computer and use it in GitHub Desktop.
Save lamprosg/2436540 to your computer and use it in GitHub Desktop.
JQuery basic use
$('document').ready(function(){
/**************************************************************/
$h1elements = $("h1"); //Returns a jQuery element from an HTML tag
/**************************************************************/
//use add to add the h2 elements to $h1elements
$h1andH2elements = $("h1").add("h2");
/**************************************************************/
//select the last div
$lastDiv = $("div").last();
//select the first div
$firstDiv = $("div").first();
//select the third from last div
$thirdFromLastDiv = $("div").eq(-3);
//select the 2d div
$second = $("div").eq(1);
/**************************************************************/
//Select all divs with class "selectMe"
$selectdivs = $('div').filter(".selectMe");
/**************************************************************/
//use .not() to get all of the divs except the third one
$thirdDiv = $('div').eq(2);
$allButTheThird = $allTheDivs.not($thirdDiv);
/**************************************************************/
//Select all children elements of div
$children = $("div").children();
/**************************************************************/
//find descendents of the div with id 'divOne'
//that are span elements
$spanDescendants = $("div#divOne").find("span");
/**************************************************************/
//Get the parent of Div
$parent= $("div").parent();
//Get all the parents of Div
$parents= $("div").parents();
/**************************************************************/
//select the span with id 'thing'
$thingSpan = $("span#thing");
//use closest() to find the nearest h1
$nearestH1 = $thingSpan.closest("h1")
/**************************************************************/
$content= $("div").html(); //Returns the html content of div
$content.html("<b>Hi</b>"); //Set the content of div to <b>Hi</b>
/**************************************************************/
$content.width(); //Get width
$content.height(); //Get height
$content.width(50); //Set width to 50
$content.height(50); //Set heightto 50
/**************************************************************/
$myElement.css('margin-left'); //returns the current value of the specified attribute
$myElement.css('margin-left',20); //Will set the left margin of $myElement to 20 pixels
/**************************************************************/
$myElement.addClass(); //adds the class passed as an argument
$myElement.removeClass(); //removes the class or list of classes passed in.
//If it is called without an argument, all classes are removed;
$myElement.hasClass(;: //check if an element has a class (returns true or false)
$myElement.toggleClass(); //Adds a class if it is not there, remove it if it is.
/**************************************************************/
$myElement.isArray() //Returns true if the object passed to it is an array, and false otherwise
/**************************************************************/
//jQuery provides a convenient method for getting and setting attributes
$link = $('a#contact'); //Link with id "contact"
var titlevalue = $link.attr('title') //Returns the value stored at the attribute "title"
//Ex. <a href="" id="contact" title="Contact us">Contact URL</a>.
$link.attr('title','E-mail us') //Change "Contact us" to "E-mail us"
/**************************************************************/
/*
<ul>
<li>foo</li>
<li>bar</li>
</ul>
*/
// The .each() method is designed to make DOM looping constructs concise and less error-prone
$('li').each(function(index) {
alert(index + ': ' + $(this).text());
});
/**************************************************************/
$("p").append(" <b>Hello world!</b>");
//The append() method inserts specified content at the end of (but still inside) the selected elements
//contentcan be a DOM element, HTML string, or jQuery object to insert at the end of each element.
$("p").prepend(" <b>Hello world!</b>");
//This will insert inside and at the beginning of the selected elements
/**************************************************************/
//jQuery allows you to create completely new elements
//The most simple method is simply passing an HTML string to $(). For example create a new div with id 'new-div'
$newDiv = $("<div id='new-div'>"); //This will return a new jQuery object on the element just created. Awesome!
$('body').append($newDiv);
//Appending existing elements (selected jquery objects) will move them to the new position, not copy them
/**************************************************************/
//This would create an image with 'src' and 'alt' attributes as given.
$('<img/'>,{
src : 'codecademy.com/logo',
alt : 'codecademy logo'
})
/**************************************************************/
/*
<div class="container">
<h2>Greetings</h2>
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
*/
$('<p>Test</p>').insertBefore('.inner'); //Self-explained
//Result:
/*
<div class="container">
<h2>Greetings</h2>
<p>Test</p>
<div class="inner">Hello</div>
<p>Test</p>
<div class="inner">Goodbye</div>
</div>
*/
//Same with insertAfter()
/**************************************************************/
//after() and before() are similar
$('.inner').after('<p>Test</p>');
$('.container').after($('h2')); //Selecting existing elements will move them to the new position, not copy them
/**************************************************************/
$('a').wrap($('<span/>')) //will wrap every <a> in a <span>
$('.inner').wrap('<div class="new" />');
/*
<div class="container">
<div class="new">
<div class="inner">Hello</div>
</div>
<div class="new">
<div class="inner">Goodbye</div>
</div>
</div>
*/
$("p").wrap("<div></div>"); //Wrap a new div around all of the paragraphs.
/**************************************************************/
//If you want to copy existing elements and not move them use clone()
//.clone() returns a deep copy of the element on which it is called.
// That means that you get a new copy of the element itself, but also all of its children.
//If you call .clone(true), all of the elements' events, attributes, and data are cloned too.
$("div#menu").clone(true) //clone the entire menu
/**************************************************************/
//Deleting and removing elements
//.html("") could cause memory leaks
$("div").empty() //removes every element that is a descendent of the element on which it is called.
//If you don't want to delete all of them you can choose what to remove
$('.hello').remove();
//or
$('div').remove('.hello');
/**************************************************************/
/**************************************************************/
/************************** Events **************************/
/**************************************************************/
/**************************************************************/
/* http://www.w3schools.com/jquery/jquery_ref_events.asp **/
/**************************************************************/
// Click event
$('#clickMe').click(function(){
})
/**************************************************************/
//The .on() method attaches event handlers to the currently selected set of elements in the jQuery object
$('#clickMe').on("click", function(){
});
$('#sampleID').on({ mouseenter: function(e) { alert('entered'); }, mouseleave: function(e) { alert('exited'); } });
/**************************************************************/
//Sometimes it can be useful to know which object triggered an event
//Knowing our event target, the element that fired the event, can make this process a lot easier
//We do this by passing the event into the anonymous function associated with our handler
//We can then refer to the target node of the event by saying event.target and turn it into a JQuery object
$('li').click(function(event){
var $target = $(event.target); //turning the event target to a jQuery object
alert($target.id); //alert the id of the target
});
//event.namespace would hold the name of the event's target, or the object that triggered the event
/**************************************************************/
$('div').offset();
var left_coord = offset.left;
var right_coord = offset.top;
//The .offset() method allows us to retrieve the current position of an element relative to the document
$('div').offset({left:10px, top:10px});
//Reposition an element.
//The element's position is specified relative to the document.
//If the element's position style property is currently static, it will be set to relative.
$('div').position(); //Retrieves the current position relative to the offset parent
/**************************************************************/
//The mousemove() event is sent to an element when the mouse pointer moves inside the element.
//Any HTML element can receive this event.
/*
Example
<div id="target">
Move here
</div>
<div id="other">
Trigger the handler
</div>
<div id="log"></div>
*/
//The event object that is passed to the handler contains some information about the mouse coordinates
$("#target").mousemove(function(event) {
var msg = "Handler for .mousemove() called at ";
msg += event.pageX + ", " + event.pageY;
$("#log").append("<div>" + msg + "</div>");
});
//Now when the mouse pointer moves within the target button, the messages are appended to <div id="log">
// .pageX and .pageY properties so that they can be used in all browsers.
//These properties provide the X and Y coordinates of the mouse pointer relative to the top-left corner of the document
//To trigger the event manually, apply .mousemove() without an argument
$("#other").click(function() {
$("#target").mousemove();
});
/**************************************************************/
//There are some convenient methods built into JQuery to alert us when the user's mouse is on a certain object
//The mouseenter() event triggers whenever the mouse enters an object
//The mouseleave() event triggers when the mouse leaves an object
//Often we simply want to know when the user is directly over an object. This can be done by using the hover() function
$("div").hover(function () {
//entry code here
},
function () {
//exit code here
}
);
/**************************************************************/
//keypress() creates an event any time a key is pressed
//For example we can have an event when a key is pressed in a textbox
/*
<form>
<fieldset>
<input id="target" type="text" value="Hello there" />
</fieldset>
</form>
<div id="other">
Trigger the handler
</div>
*/
$("#target").keypress(function() {
alert("Handler for .keypress() called.");
});
//To trigger the event manually, apply .keypress() without an argument
$('#other').click(function() {
$("#target").keypress();
});
//Note that keydown() and keyup() provide a code indicating which key is pressed
//while keypress() indicates which character was entered
//To determine which character was entered, examine the event object that is passed to the handler function.
//jQuery normalizes the .which property so you can reliably use it to retrieve the character code.
$("#target").keypress(function(event) {
if ( event.which == 13 ) {
event.preventDefault();
}
});
/**************************************************************/
//When the user starts using an object on the page it is "given" focus and the focus() event is called.
//When the user is no longer using the object is loses focus and the blur() event is called.
$('#target').focus(function() {
alert('Focus Fire');
});
//or manually
$('#other').click(function() {
$('#target').focus();
});
//Doesn't work in Internet Explorer
/**************************************************************/
//We can even use events to validate forms
/*
<p>Type 'correct' to validate.</p>
<form action="javascript:alert('success!');">
<div>
<input type="text" />
<input type="submit" />
</div>
</form>
<span></span>
*/
$("form").submit(function() {
if ($("input:first").val() == "correct") {
$("span").text("Validated...").show();
return true;
}
$("span").text("Not valid!").show().fadeOut(1000);
return false;
});
/**************************************************************/
/**************************************************************/
/************************** Effects ***************************/
/**************************************************************/
/**************************************************************/
/**************************************************************/
//Bounces 3 times when clicking on the element.
$("div").click(function () {
$(this).effect("bounce", { times:3 }, 300);
});
/**************************************************************/
//Animations
/*
<div id="clickme">Click here</div>
<img id="book" src="book.png" alt="" width="100" height="123"
style="position: relative; left: 10px;" />
*/
$('#clickme').click(function() {
$('#book').animate({
opacity: 0.25,
left: '+=50',
height: 'toggle'
}, 5000, function() {
// Animation complete.
});
});
//Note that the target value of the height property is 'toggle'.
//Since the image was visible before, the animation shrinks the height to 0 to hide it.
//A second click then reverses this transition
/**************************************************************/
//delay() method allows us to delay the execution of functions that follow it in the queue
//Durations are given in milliseconds; higher values indicate slower animations, not faster ones.
//The strings 'fast' and 'slow' can be supplied to indicate durations of 200 and 600 milliseconds, respectively.
$('#foo').slideUp(300).delay(800).fadeIn(400);
//When this statement is executed, the element slides up for 300 milliseconds
//pauses for 800 milliseconds
//before fading in for 400 milliseconds.
/**************************************************************/
//Fade in
$('#clickme').click(function() {
$('#book').fadeIn('slow', function() {
// Animation complete
});
});
//Fade out
$('#clickme').click(function() {
$('#book').fadeOut('slow', function() {
// Animation complete.
});
});
/**************************************************************/
//Show
$("button").click(function () {
$("p").show("slow");
});
/*<button id="showr">Show</button>
<button id="hidr">Hide</button>
<div>Hello 3,</div>
<div>how</div>
<div>are</div>
<div>you?</div>
*/
<script>
$("#showr").click(function () {
$("div").first().show("fast", function showNext() {
$(this).next("div").show("fast", showNext);
});
});
$("#hidr").click(function () {
$("div").hide(1000);
});
</script>
//Same with hide()
/**************************************************************/
//Example with show() and slideup()
$(document.body).click(function () {
if ($("div:first").is(":hidden")) {
$("div").show("slow");
} else {
$("div").slideUp();
}
});
//Same with slideDown()
/**************************************************************/
//On and off
$("button").click(function () {
$("p").slideToggle("slow");
});
/**************************************************************/
//When .stop() is called on an element, the currently-running animation (if any) is immediately stopped.
/* Start animation */
$("#go").click(function(){
$(".block").animate({left: '+=100px'}, 2000);
});
/* Stop animation when button is clicked */
$("#stop").click(function(){
$(".block").stop();
});
/* Start animation in the opposite direction */
$("#back").click(function(){
$(".block").animate({left: '-=100px'}, 2000);
});
/**************************************************************/
/**************************************************************/
/**************************************************************/
/*************************jQuery UI plugin*********************/
/**************************************************************/
//<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
/**************************************************************/
//Make things dragable
$("#dragme").draggable();
//Make things sortable
/*
<ul id="sortable">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
<li>Item 7</li>
</ul>
*/
$( "#sortable" ).sortable();
$( "#sortable" ).disableSelection();
//Make things resizable
$( "img" ).resizable();
/**************************************************************/
//There's an addClass() function in jQuery UI also but with added animation
$( "#myDiv" ).addClass( "red", 500, callback);
//"red" is the class to add to myDiv, 500 is the time for the animation to happen
//callback is the optional function to run at the completion of the animation
function callback() {
setTimeout(function() {
$( "#effect" ).removeClass( "newClass" );
}, 1500 );
}
/**************************************************************/
//Animate with jQuery UI
$( "#button" ).toggle(
function() {
$( "#effect" ).animate({
backgroundColor: "#aa0000",
color: "#fff",
width: 500
}, 1000 );
},
function() {
$( "#effect" ).animate({
backgroundColor: "#fff",
color: "#000",
width: 240
}, 1000 );
}
);
/**************************************************************/
//Autocomplete
/*<input id="tags">*/
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$( "#tags" ).autocomplete({
source: availableTags
});
/**************************************************************/
//Datepicker
$(function() {
$( "#datepicker" ).datepicker();
});
/**************************************************************/
//Slider
/*<div class="selector"></div>*/
/*<script>*/
$(function() {
$( ".selector" ).slider();
});
/*</script>*/
//The minimum value of the slider. (The same with "max" instead of "min")
//Initialize a slider with the min option specified.
$( ".selector" ).slider({ min: -7 });
//Get or set the min option, after init.
//getter
var min = $( ".selector" ).slider( "option", "min" );
//setter
$( ".selector" ).slider( "option", "min", -7 );
//Orientation
$( ".selector" ).slider({ orientation: "vertical" });
//Step
$( ".selector" ).slider({ step: 5 });
//Initialize a slider with the value option specified.
$( ".selector" ).slider({ value: 37 });
//Get or set the value option, after init.
//getter
var value = $( ".selector" ).slider( "option", "value" );
//setter
$( ".selector" ).slider( "option", "value", 37 );
//Initialize a slider with the values option specified.
$( ".selector" ).slider({ values: [1,5,9] });
//Get or set the values option, after init.
//getter
var values = $( ".selector" ).slider( "option", "values" );
//setter
$( ".selector" ).slider( "option", "values", [1,5,9] );
/**************************************************************/
//Tabs
/*
<div id="tabs">
<ul>
<li><a href="#tabs-1">Nunc tincidunt</a></li>
<li><a href="#tabs-2">Proin dolor</a></li>
<li><a href="#tabs-3">Aenean lacinia</a></li>
</ul>
<div id="tabs-1">
<p>Proin elit arcu, rutrum commodo, vehicula tempus, commodo a, risus. Curabitur nec arcu. Donec sollicitudin mi sit amet mauris. Nam elementum quam ullamcorper ante. Etiam aliquet massa et lorem. Mauris dapibus lacus auctor risus. Aenean tempor ullamcorper leo. Vivamus sed magna quis ligula eleifend adipiscing. Duis orci. Aliquam sodales tortor vitae ipsum. Aliquam nulla. Duis aliquam molestie erat. Ut et mauris vel pede varius sollicitudin. Sed ut dolor nec orci tincidunt interdum. Phasellus ipsum. Nunc tristique tempus lectus.</p>
</div>
<div id="tabs-2">
<p>Morbi tincidunt, dui sit amet facilisis feugiat, odio metus gravida ante, ut pharetra massa metus id nunc. Duis scelerisque molestie turpis. Sed fringilla, massa eget luctus malesuada, metus eros molestie lectus, ut tempus eros massa ut dolor. Aenean aliquet fringilla sem. Suspendisse sed ligula in ligula suscipit aliquam. Praesent in eros vestibulum mi adipiscing adipiscing. Morbi facilisis. Curabitur ornare consequat nunc. Aenean vel metus. Ut posuere viverra nulla. Aliquam erat volutpat. Pellentesque convallis. Maecenas feugiat, tellus pellentesque pretium posuere, felis lorem euismod felis, eu ornare leo nisi vel felis. Mauris consectetur tortor et purus.</p>
</div>
<div id="tabs-3">
<p>Mauris eleifend est et turpis. Duis id erat. Suspendisse potenti. Aliquam vulputate, pede vel vehicula accumsan, mi neque rutrum erat, eu congue orci lorem eget lorem. Vestibulum non ante. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Fusce sodales. Quisque eu urna vel enim commodo pellentesque. Praesent eu risus hendrerit ligula tempus pretium. Curabitur lorem enim, pretium nec, feugiat nec, luctus a, lacus.</p>
<p>Duis cursus. Maecenas ligula eros, blandit nec, pharetra at, semper at, magna. Nullam ac lacus. Nulla facilisi. Praesent viverra justo vitae neque. Praesent blandit adipiscing velit. Suspendisse potenti. Donec mattis, pede vel pharetra blandit, magna ligula faucibus eros, id euismod lacus dolor eget odio. Nam scelerisque. Donec non libero sed nulla mattis commodo. Ut sagittis. Donec nisi lectus, feugiat porttitor, tempor ac, tempor vitae, pede. Aenean vehicula velit eu tellus interdum rutrum. Maecenas commodo. Pellentesque nec elit. Fusce in lacus. Vivamus a libero vitae lectus hendrerit hendrerit.</p>
</div>
</div>*/
/*<script>*/
$(function() {
$( "#tabs" ).tabs();
});
/*</script>*/
/***************** http://jqueryui.com/docs/Getting_Started ************/
});
/**GET*******************************************/
$.ajax({ //Send using AJAX
type: "GET",
url: "updateDatabase.php",
data: "mylat="+mylat+"&mylng="+mylng,
success: function(){
},
error: function(){
}
});
$.ajax({ //Get using AJAX
type: "GET",
url: "updateDatabase.php",
data: "mylat="+mylat+"&mylng="+mylng,
success: function(data, textStatus, jqXHR){ //jqXHR is the XMLHttpRequest object.
var output = jqXHR.responseText; //responseXML will get an XML
},
error: function(){
}
});
// Load and execute a JavaScript file.
$.ajax({
type: "GET",
url: "test.js",
dataType: "script"
});
/************************************************/
/**POST******************************************/
$.ajax({ //Save some data to the server and notify the user once it's complete.
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
//Send an xml document as data to the server.
//By setting the processData option to false, the automatic conversion of data to strings is prevented.
var xmlDocument = [create xml document];
var xmlRequest = $.ajax({
url: "page.php",
processData: false,
data: xmlDocument
});
xmlRequest.done(handleResponse);
/************************************************/
@lamprosg
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment