jQuery

basics

jQuery is good... but heavy

jQuery is awesome!

Adding jQuery to Web Pages

There are a lot of...

Download a file and link it

Go To http://jquery.com/download and download one

<script src="jquery-1.12.3.min.js"></script>

Link script to your project

Full (Development) file

<script src="jquery-1.12.3.js"></script>

Compressed (Production) file

<script src="jquery-1.12.3.min.js"></script>

Include jQuery via CDN

Google CDN:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>

Microsoft CDN:

<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.3.min.js"></script>

jQuery via NODE.JS

npm install -S 'jquery@>=2.1'

npm install -S 'jsdom@3.1.2'

jQuery versions

jQuery 1.x

Support most browsers

jQuery 2.x

Does not support old browsers, like IE<9. Smaller than 1.x

jQuery 3.0

jQuery Compat 3.0

Support only modern browsers

Support old browsers

latest:  1.12.3

latest:  2.2.3

http://code.jquery.com/jquery-latest.js

Selectors

Basic Selectors

Tag name

Class

Id

$( "p" )
$( ".rolling" )
$( "#scopes" )

Hierarchy

parent > child

ancestor descendant

prev + next

prev ~ siblings

$( "form input" )
$( "#main > *" )
$( "label + input" )
$( "#prev ~ div" )

Filters

Mmm... Pure DOM elements

Basic Filters

:not()

:first / :last

:even / :odd

.eq( index ) / :gt( index ) / :lt( index ) 

:header

:animated

$( "tr:first" )
$( "input:not(:checked) + span" )
$( "tr:even" )
$( "td:eq( 2 )" )
$( ":header" )
$( "div:animated" )

Content Filters

:empty

:contains( text )

:has( selector )

.parent

$( "div:contains('John')" )
$( "td:empty" )
$( "div:has(p)" )
$( "td:parent" )

Visibility Filters

:visible

:hidden

$( "div:hidden" )
$( "div:visible" )

Attribute Filters

[ attribute=value ] / [ attribute!=value ]

[ attribute ]

[ attribute^=value ] / [ attribute$=value ] / [ attribute*=value ]

[ attributeFilter1 ][ attributeFilter2 ][ attributeFilter3 ]

$( "div[id]" )
$( "input[name='newsletter']" )
$( "input[name^='news']" )
$( "input[id][name$='man']" )

Child Filters

:first-child

:nth-child( index / even / odd / formula )

:last-child

:only-child

$( "ul li:nth-child(3n)" )
$( "div span:first-child" )
$( "div span:last-child" )
$( "div button:only-child" )

Forms

:text / :password

:input

:radio / :checkbox

:submit / :button

$( ":input" )
$( "form input:text" )
$( "form input:radio" )
$( ":submit" )

:image / :reset / :file 

$( ":image" )

Form Filters

:disabled

:enabled

:checked

:selected

$( "input:enabled" )
$( "input:disabled" )
$( "input:checked" )
$( "select option:selected" )

Attributes

... just add few attributes

Attr

.attr( properties )

.attr( name )

.attr( key, value )

.attr( key, function )

.removeAttr( name )

var title = $( "img" ).attr( "title" );
$( "img" ).attr({
    src: "/images/hat.gif",
    title: "jQuery",
    alt: "jQuery Logo"
});
$( "button:gt(1)" ).attr( "disabled", "disabled" );
$( "div" ).attr( "id", function(i, val) {
      return "div-id" + i + val;
});
$( "button" ).removeAttr( "disabled" );

Class

.hasClass( class )

.addClass( class )

.removeClass( class )

.toggleClass( class )

$( "p:last" ).addClass( "selected" );
var rightString = $( "p:first" ).hasClass( "selected" );
$( "p:even" ).removeClass( "blue" );
$( "h2" ).toggleClass( "highlight" );

.toggleClass( class, state )

$( "p.hamlet" ).toggleClass( "question", toBeOrNotToBe );

HTML

.html( value )

.html( )

var content = $( "p" ).html();
$( "div" ).html( "<span class='red'>Hello <b>Again</b></span>" );

Text

.text( value )

.text( )

var str = $( "p:first" ).text();
$( "p" ).text( "<b>Some</b> new text." );

Value

.val( value )

.val( )

var multipleValues = $( "#multiple" ).val() || [];
$( "input" ).val( "Enter Password" );

Traversing

Walking around DOM tree

Filtering

.first( ) / .last( )

.eq( ) / .filter ( )

.has( )

.is( )

.not( )

.slice( )

$("li").eq(5)
$("p span").first()
$("li").has("ul")
$(event.target).is("li")
$("li").not(":even")
$("li").slice(2)

Tree traversing

.next( ) / .nextAll( ) / .nextUntil( ) 

.children( ) / .closest( ) / .find( )

.offsetParent( ) / .parent( ) / .parents( ) / .parentsUntil( )

.prev( ) / .prevAll( ) / .prevUntil( ) 

$("ul.level-2").children()
$("li.third-item").next()
$("li.item-a").parent()
$("li.third-item").prev()

.siblings( )

$("li.third-item").siblings()

Miscellaneous Traversing

.addBack( )

.add( )

.contents( )

.end( )

$("p").add("div")
$("div.after-addback").find("p").addBack()
$("#frameDemo").contents()
$( "ul.first" )
  .find( ".foo" )
    .css( "background-color", "red" )
  .end()
  .find( ".bar" )
    .css( "background-color", "green" );

Array workaround

.map( callback )

Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.

$( ":checkbox" ).map(function() {
    return this.id;
  }).get().join();

.each( callback )

Iterate over a jQuery object, executing a function for each matched element.

$( "li" ).each(function( index ) {
  console.log( index + ": " + $( this ).text() );
});

DOM element methods 

.index( ) / .index( selector ) / .index( element )

.get( index ) / .get( )

.toArray( )

console.log( $( "li" ).get( 0 ) );
alert( "Index: " + $( "#bar" ).index() );
alert( $( "li" ).toArray() );

DOM manipulation

Build DOM your way

... Okay

DOM insertion, inside

.appendTo( )

.append( )

.prepend( )

.prependTo( )

$(".container").append($("h2"));
$("h2").appendTo($(".container"));
$( ".inner" ).prepend( "<p>Test</p>" );
$( "<p>Test</p>" ).prependTo( ".inner" );

DOM insertion, outside

.insertAfter( )

.after( )

.before( )

.insertBefore( )

$( ".container" ).after( $( "h2" ) );
$( "h2" ).insertAfter( $( ".container" ) );
$( ".inner" ).before( "<p>Test</p>" );
$( "<p>Test</p>" ).insertBefore( ".inner" );

DOM insertion, around

.wrap( )

.unwrap( )

.wrapAll( )

.wrapInner( )

$( "p" ).unwrap();
$( ".inner" ).wrap( "<div class='new'></div>" );
$( ".inner" ).wrapAll( "<div class='new'></div>");
$( ".inner" ).wrapInner( "<div class='new'></div>");

DOM replacement

.replaceWith( )

.replaceAll( )

$( "<h2>New heading</h2>" ).replaceAll( ".inner" );
$( "div.second" ).replaceWith( "<h2>New heading</h2>" );

DOM removal

.detach( )

.remove( )

.empty( )

$( ".hello" ).remove();
var p = $( "p" ).detach();
$( ".hello" ).empty();

.clone( [withDataAndEvents] )

Create a deep copy of the set of matched elements.

// Original element with attached data
var $elem = $( "#elem" ).data( "arr", [ 1 ] ),
    $clone = $elem.clone( true )
        // Deep copy to prevent data sharing
        .data( "arr", $.extend( [], $elem.data( "arr" ) ) );

Deep cloning

$( ".hello" ).clone().appendTo( ".goodbye" );

CSS workaround

Just make it pretty and sell for ...

80 million $

.css( )

Get the computed style properties for the first element in the set of matched elements.

var color = $( "h2" ).css( "background-color" );

.css( propertyName )

Set one or more CSS properties for the set of matched elements.

$( "div.example" ).css( "width", function( index ) {
  return index * 50;
});

.css( propertyName, propertyValue )

Position

.position( )

.offset( )

.scrollTop( ) / .scrollLeft( )

var p = $( "p:last" );
var offset = p.offset();
p.html( "left: " + offset.left +
", top: " + offset.top );
var p = $( "p:first" );
var position = p.position();
$( "p:last" ).text( "left: " + position.left +
", top: " + position.top );
var p = $( "p:first" );
$( "p:last" ).text( "scrollTop:" + p.scrollTop() );

Width and Height

.height( ) / .outerHeight( ) / .innerHeight( )

.width( ) / .outerWidth( ) / .innerWidth( )

var modWidth = 50;
$( "div" ).one( "click", function() {
  $( this ).width( modWidth ).addClass( "mod" );
  modWidth -= 8;
});
$( "div" ).on( "click", function() {
  $( this ).height( 30 ).css({
    cursor: "auto",
    backgroundColor: "green"
  });
});

Events

HOVER

Browser events

Bind an event handler to the "resize" JavaScript event, or trigger that event on an element.

$( window ).resize(function() {
  $( "#log" ).append( "<div>Handler for .resize() called.</div>" ); });

.resize( )

Bind an event handler to the "scroll" JavaScript event, or trigger that event on an element.

$( "#target" ).scroll(function() {
  $( "#log" ).append( "<div>Handler for .scroll() called.</div>" ); });

.scroll( )

Document loading

Specify a function to execute when the DOM is fully loaded.

$( document ).ready(function() {
  // Handler for .ready() called.
});

.ready( )

.on( )

Attach an event handler function for one or more events to the selected elements.

$( "p" ).on( "click", function() {
  alert( $( this ).text() );
});

Event Handler Attachment

.delegate( ) / .undelegate( )

.bind( ) / .unbind( )

$( "p" ).bind( "click", function() {
  alert( $( this ).text() );
});
$( "body" ).delegate( "p", "click", function() {
  alert( $( this ).text() );
});

Trigger / remove handler

Execute all handlers and behaviors attached to the matched elements for the given event type.

$( "#foo" ).on( "click", function() {
  alert( $( this ).text() );
});
$( "#foo" ).trigger( "click" );

.trigger( )

Remove an event handler.

$( "p" ).off();

.off( )

Mouse events

.contextmenu( )

.click( )

.dblclick( )

.hover( )

$( selector ).click( handler );
$( selector ).contextmenu( handler );
$( selector ).dblclick( handler );
$( selector ).hover( handlerIn, handlerOut );

.mouseenter( ) / .mouseleave( )

$( selector ).mouseenter( handlerIn ).mouseleave( handlerOut );

Keyboard events

.keydown( )

.keypress( )

.keyup( )

$( "#target" ).keypress(function() {
  console.log( "Handler for .keypress() called." );
});
$( "#target" ).keydown(function() {
  alert( "Handler for .keydown() called." );
});
$( "#target" ).keyup(function() {
  alert( "Handler for .keyup() called." );
});

Effects

Let's add some magic!

Basic effects

.show( )

.hide( )

.toggle( )

$( "p" ).hide();
$( "p" ).show( "slow" );
$( "#book" ).toggle( "slow", function() {
    // Animation complete.
  });

Sliding

.slideUp( )

.slideDown( )

.slideToggle( )

$( "div" ).slideDown( "slow" );
$( "div" ).slideUp();
$( "#book" ).slideToggle( "slow", function() {
    // Animation complete.
  });

Fading

.fadeOut( )

.fadeIn( )

.fadeTo( )

.fadeToggle( )

$( "div:hidden:first" ).fadeIn( "slow" );
$( "#box1" ).fadeOut( 1600, "linear", complete );
$( "div.ghost" ).fadeTo( "slow", 0.33 );
$( "p:first" ).fadeToggle( "slow", "linear" );

Custom effects

Execute all handlers and behaviors attached to the matched elements for the given event type.

$( "#book" ).animate({
    opacity: 0.25,
    left: "+=50",
    height: "toggle"
  }, 5000, function() {
    // Animation complete.
  });

.animate( )

$( "#foo" ).slideUp( 300 ).delay( 800 ).fadeIn( 400 );

.delay( ) / .finish( ) / .stop( )

Data

Data

Store arbitrary data associated with the matched elements.

$( "body" ).data( "foo", 52 );
$( "body" ).data( "bar", { myType: "test", count: 40 } );
$( "body" ).data( { baz: [ 1, 2, 3 ] } );
$( "body" ).data( "foo" ); // 52
$( "body" ).data(); // everything

.data( )

Remove a previously-stored piece of data.

$( "div" ).removeData( "test1" );

.removeData( )

jQuery.Data

tore arbitrary data associated with the specified element. Returns the value that was set.

jQuery.data( document.body, "foo", 52 );
jQuery.data( document.body, "bar", "test" );

jQuery.data( )

Remove a previously-stored piece of data.

jQuery.removeData( div, "test1" );

jQuery.removeData( )

This vs $(this)

Links

Authors contacts

Darya Sabinina

Sergey Shaliapin

live:darya_sabinina

darya_sabinina@epam.com

ra_Levis

Siarhei_Shaliapin@epam.com

jQuery tutorial

By Sergey Shalyapin

jQuery tutorial

  • 2,419