jQuery Documentation
Compiled by Pat Esty, 2017
HTML files must include:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js" />
OR
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.0.min.js" />
OR
<script src="./localdir/jquery-3.2.0.min.js" />
Syntax Description of jQuery Selector
================ ============================================
$("*") Selects all elements
$(this) Selects the current HTML element - (do not use quotes)
$("#mydivname") Selects the id="mydivname" object- (must use a '#' sign)
$(".classname") Select all elements with class="classname") - notice '.' dot
$("p") Select all <p> elements
$("p.intro") Selects all <p> elements with class="intro"
$("p:first") Selects the first <p> element
$("ul li:first") Selects the first <li> element of the first <ul>
$("ul li:first-child") Selects the first <li> element of every <ul>
$("[href]") Selects all elements with an href attribute
$("a[target='_blank']") Selects all <a> elements with a target attribute value equal to "_blank"
$("a[target!='_blank']") Selects all <a> elements with a target attribute value NOT equal to "_blank"
$(":button") Selects all <button> elements and <input> elements of type="button"
$("tr:even") Selects all even <tr> elements
$("tr:odd") Selects all odd <tr> elements
EXAMPLE:
-----------------
$(document).ready(function(){
$("button").click(function(){
$(".test").hide();
});
});
COMMON DOM EVENTS
-----------------
Mouse Events Keyboard Events Form Events Doc/Window Events
============ =============== =========== =================
click keypress submit load
dblclick keydown change resize
mouseenter keyup focus scroll
mouseleave blur unload
EXAMPLE:
-------------------------
$("p").click(function(){
// action goes here!!
});
BETTER SYNTAX:
-------------------------
$("p").on("click", function(){
$(this).hide();
});
OR
$("p").on({
mouseenter: function(){
$(this).css("background-color", "lightgray");
},
mouseleave: function(){
$(this).css("background-color", "lightblue");
},
click: function(){
$(this).css("background-color", "yellow");
}
});
HOVER NEEDS TWO EVENTS: (one to enter, one to leave the hover)
----------------------- --------------------------------------
$("#p1").hover(function(){
alert("You entered p1!");
},
function(){
alert("Bye! You now leave p1!");
});
VARIOUS FUNCTIONs of SELECTORS: (where "callback" is an optional param)
===============================
$(selector).hide(spped,callback); //speed is always in milliseconds
$(selector).show(speed,callback); //or the words slow or fast
$(selector).toggle(speed,callback);
OTHERS:
animate() Runs a custom animation on the selected elements
stop() Stops the currently running animation for the selected elements
clearQueue() Removes all remaining queued functions from the selected elements
delay() Sets a delay for all queued functions on the selected elements
dequeue() Removes the next function from the queue, and then executes the function
fadeIn() Fades in the selected elements
fadeOut() Fades out the selected elements
fadeTo() Fades in/out the selected elements to a given opacity
fadeToggle() Toggles between the fadeIn() and fadeOut() methods
finish() Stops, removes and completes all queued animations for the selected
queue() Shows the queued functions on the selected elements
slideDown() Slides-down (shows) the selected elements
slideToggle() Toggles between the slideUp() and slideDown() methods
slideUp() Slides-up (hides) the selected elements
jQuery HTML / CSS Methods
----------------------------
Method Description
============ ============================================
addClass() Adds one or more class names to selected elements
after() Inserts content after selected elements
append() Inserts content at the end of selected elements
appendTo() Inserts HTML elements at the end of selected elements
attr() Sets or returns attributes/values of selected elements
before() Inserts content before selected elements
clone() Makes a copy of selected elements
css() Sets or returns one or more style properties for selected elements
detach() Removes selected elements (keeps data and events)
empty() Removes all child nodes and content from selected elements
hasClass() Checks if any of the selected elements have a specified class name
height() Sets or returns the height of selected elements
html() Sets or returns the content of selected elements
innerHeight() Returns the height of an element (includes padding, but not border)
innerWidth() Returns the width of an element (includes padding, but not border)
insertAfter() Inserts HTML elements after selected elements
insertBefore() Inserts HTML elements before selected elements
offset() Sets or returns the offset coordinates for selected elements (relative to the document)
offsetParent() Returns the first positioned parent element
outerHeight() Returns the height of an element (includes padding and border)
outerWidth() Returns the width of an element (includes padding and border)
position() Returns the position (relative to the parent element) of an element
prepend() Inserts content at the beginning of selected elements
prependTo() Inserts HTML elements at the beginning of selected elements
prop() Sets or returns properties/values of selected elements
remove() Removes the selected elements (including data and events)
removeAttr() Removes one or more attributes from selected elements
removeClass() Removes one or more classes from selected elements
removeProp() Removes a property set by the prop() method
replaceAll() Replaces selected elements with new HTML elements
replaceWith() Replaces selected elements with new content
scrollLeft() Sets or returns the horizontal scrollbar position of selected elements
scrollTop() Sets or returns the vertical scrollbar position of selected elements
text() Sets or returns the text content of selected elements
toggleClass() Toggles between adding/removing one or more classes from selected
unwrap() Removes the parent element of the selected elements
val() Sets or returns the value attribute of the selected elements (for form elements)
width() Sets or returns the width of selected elements
wrap() Wraps HTML element(s) around each selected element
wrapAll() Wraps HTML element(s) around all selected elements
wrapInner() Wraps HTML element(s) around the content of each selected element
jQuery Traversing Methods
----------------------------
Method Description
============ ============================================
add() Adds elements to the set of matched elements
addBack() Adds the previous set of elements to the current set
andSelf() Deprecated in version 1.8. An alias for addBack()
children() Returns all direct children of the selected element
closest() Returns the first ancestor of the selected element
contents() Returns all direct children of the selected element
(including text and comment nodes)
each() Executes a function for each matched element
end() Ends the most recent filtering operation in the current chain,
and return the set of matched elements to its previous state
eq() Returns an element with a specific index number of the
selected elements
filter() Reduce the set of matched elements to those that match the selector
or pass the function's test
find() Returns descendant elements of the selected element
first() Returns the first element of the selected elements
has() Returns all elements that have one or more elements inside of them
is() Checks the set of matched elements against a selector/element/jQuery
object, and return true if at least one of these elements matches
the given arguments
last() Returns the last element of the selected elements
map() Passes each element in the matched set through a function,
producing a new jQuery object containing the return values
next() Returns the next sibling element of the selected element
nextAll() Returns all next sibling elements of the selected element
nextUntil() Returns all next sibling elements between two given arguments
not() Remove elements from the set of matched elements
offsetParent() Returns the first positioned parent element
parent() Returns the direct parent element of the selected element
parents() Returns all ancestor elements of the selected element
parentsUntil() Returns all ancestor elements between two given arguments
prev() Returns the previous sibling element of the selected element
prevAll() Returns all previous sibling elements of the selected element
prevUntil() Returns all previous sibling elements between two given arguments
siblings() Returns all sibling elements of the selected element
slice() Reduces the set of matched elements to a subset specified
by a range of indices
jQuery AJAX Methods
----------------------------
AJAX is the art of exchanging data with a server, and update parts of a
web page - without reloading the whole page.
The following table lists all the jQuery AJAX methods:
Method Description
============ ============================================
$.ajax() Performs an async AJAX request
$.ajaxPrefilter() Handle custom Ajax options or modify existing options before
each request is sent and before they are processed by $.ajax()
$.ajaxSetup() Sets the default values for future AJAX requests
$.ajaxTransport() Creates an object that handles the actual transmission of Ajax data
$.get() Loads data from a server using an AJAX HTTP GET request
$.getJSON() Loads JSON-encoded data from a server using a HTTP GET request
$.parseJSON() Deprecated in version 3.0, use JSON.parse() instead.
Takes a well-formed JSON string and returns the resulting
JavaScript value
$.getScript() Loads (and executes) a JavaScript from a server using an
AJAX HTTP GET request
$.param() Creates a serialized representation of an array or object
(can be used as URL query string for AJAX requests)
$.post() Loads data from a server using an AJAX HTTP POST request
ajaxComplete() Specifies a function to run when the AJAX request completes
ajaxError() Specifies a function to run when the AJAX request completes
with an error
ajaxSend() Specifies a function to run before the AJAX request is sent
ajaxStart() Specifies a function to run when the first AJAX request begins
ajaxStop() Specifies a function to run when all AJAX requests have completed
ajaxSuccess() Specifies a function to run when an AJAX request completes
successfully
load() Loads data from a server and puts the returned data into
the selected element
serialize() Encodes a set of form elements as a string for submission
serializeArray() Encodes a set of form elements as an array of names and values
jQuery Misc Methods
Method Description
============ ============================================
data() Attaches data to, or gets data from, selected elements
each() Execute a function for each matched element
get() Get the DOM elements matched by the selector
index() Search for a given element from among the matched elements
$.noConflict() Release jQuery's control of the $ variable
$.param() Create a serialized representation of an array or object
(can be used as URL query string for AJAX requests)
removeData() Removes a previously-stored piece of data
size() Removed in version 3.0. Use the length property instead.
toArray() Retrieve all the DOM elements contained in the jQuery set,
as an array
jQuery Properties
Method Description
============ ============================================
context Removed in version 3.0. Contains the original context passed
to jQuery()
jquery Contains the jQuery version number
jQuery.fx.interval Change the animation firing rate in milliseconds
jQuery.fx.off Globally disable/enable all animations
jQuery.support A collection of properties representing different browser
features or bugs (Intended for jQuery's internal use)
length Contains the number of elements in the jQuery object
This moves a particular image based on the up/down/left/right keys presssed:
$(document).ready(function() {
$(document).keydown(function(key) {
switch(parseInt(key.which,10)) {
// Left arrow key pressed
case 37:
$('img').animate({left: "-=10px"}, 'fast');
break;
// Up Arrow Pressed
case 38:
$('img').animate({top: "-=10px"}, 'fast');
break;
// Right Arrow Pressed
case 39:
$('img').animate({left: "+=10px"}, 'fast');
break;
// Down Arrow Pressed
case 40:
$('img').animate({top: "+=10px"}, 'fast');
break;
}
});
});
AlSO TRY:
=-=-=-=-=:
$(this).effect('explode');
$(this).effect('bounce', {times:3}, 500); //in milliseconds
$("#menu").accordion({collapsible: true, active: false});
ACCORDIAN EXAMPLE:
=================
<!DOCTYPE html>
<html>
<head>
<title>Behold!</title>
<link rel='stylesheet' type='text/css' href='http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css'/>
<script type='text/javascript' src='script.js'></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
</head>
<body>
<div id="menu">
<h3>jQuery</h3>
<div>
<p>jQuery is a JavaScript library
that makes your websites look absolutely stunning.</p>
</div>
<h3>jQuery UI</h3>
<div>
<p>jQuery UI includes even more jQuery goodness!</p>
</div>
<h3>JavaScript</h3>
<div>
<p>JavaScript is a programming language used in web browsers,
and it's what powers jQuery and jQuery UI. You can learn about
JavaScript in the JavaScript track on Codecademy.
</div>
</div>
</body>
</html>