jQuery Fundamentals
0
The jQuery library provides the jQuery function,
1 |
var listItems = jQuery( 'li' ); |
Is same as…
1 |
var listItems = $( 'li' ); |
Which select all ‘li’ elements. The following ensures the page is ready for jQuery operations.
1 |
$(document).ready() |
Is same as…
1 |
$() |
Example:
1 2 3 4 |
// $( document ).ready(function() { $(function() { console.log( 'ready!' ); }); |
Get some elements from a page
1 2 3 4 |
$( '#header' ); // select the element with an ID of 'header' $( 'li' ); // select all list items on the page $( 'ul li' ); // select list items that are in unordered lists $( '.person' ); // select all elements with a class of 'person' |
Filtering selections with jQuery:
1 2 3 4 5 6 7 8 9 10 |
var listItems = $( 'li' ); // filter the selection to only items with a class of 'special' var special = listItems.filter( '.special' ); // filter the selection to only items without a class of 'special' var notSpecial = listItems.not( '.special' ); // filter the selection to only items that contain a span var hasSpans = listItems.has( 'span' ); |
Events
1 2 3 |
$( '#my-unordered-list' ).on( 'click', 'li', function( event ) { console.log( this ); // logs the list item that was clicked }); |
Effects
1 2 3 4 5 6 7 |
.show() Show the selected elements. .hide() Hide the selected elements. .fadeIn() Animate the opacity of the selected elements to 100%. .fadeOut() Animate the opacity of the selected elements to 0%. .slideDown() Display the selected elements with a vertical sliding motion. .slideUp() Hide the selected elements with a vertical sliding motion. .slideToggle() Show or hide the selected elements with a vertical sliding motion. |
Custom effects with .animate()
1 2 3 4 5 6 7 8 9 10 |
$( '.funtimes' ).animate({ left: '+=50', // increase by 50 opacity: 0.25, fontSize: '12px' }, 300, function() { // executes when the animation is done } ); |
Managing animate
1 2 |
.stop() will stop currently running animations on the selected elements. .delay() will pause before the execution of the next animation method. |