JQuery

Contents

  • What is JQuery?
  • DOM Ready?
  • Attributes
  • Selectors
  • Traversing
  • CSS, Styling
  • Data Methods
  • Utility
  • Iterating
  • .index

What is JQuery

  • a JavaScript library
  • lightweight and feature-rich
  • provides easy-to-use API which makes things like
  • HTML DOM Traversal & Manipulation
  • event handling
  • animation
  • Ajax
  • Other Utilities

Syntax

  • Difference between $ vs $("")
  • Methods called on jQuery selections are in the $.fn namespace, and automatically receive and return the selection as this.
  • Methods in the $ namespace are generally utility-type methods, and do not work with selections; they are not automatically passed any arguments, and their return value will vary.
// e.g.

$( "h1" ).remove();

$.trim("")

DOM Ready?

  • A page can't be manipulated safely until the document is "ready."
$( document ).ready(function() {
    console.log( "ready!" );
});


// Shorthand for $( document ).ready()
$(function() {
    console.log( "ready!" );
});


// Passing a named function instead of an anonymous function.
 
function readyFn( jQuery ) {
    // Code to run when the document is ready.
}
 
$( document ).ready( readyFn );
// or:
$( window ).on( "load", readyFn );

Attributes

  • The .attr() method acts as both a getter and a setter.
  • As a setter, .attr() can accept either a key and a value, or an object containing one or more key/value pairs.
//attr as getter
$( "a" ).attr( "href" ); 
// Returns the href for the first a element in the document


// attr as setter
$( "a" ).attr( "href", "http://www.google.com" );
 
$( "a" ).attr({
    title: "Check Out Google",
    href: "http://www.google.com"
});

Selectors

  • "select some elements and do something with them."
  • supports most CSS3 selectors, as well as some non-standard selectors.
//Selecting Elements by ID
$( "#myId" ); // Note IDs must be unique per page. 

//link Selecting Elements by Class Name
$( ".myClass" );

//link Selecting Elements by Attribute
$( "input[name='first_name']" );

//link Selecting Elements by Compound CSS Selector
$( "#contents ul.people li" );

//link Selecting Elements with a Comma-separated List of Selectors
$( "div.myClass, ul.people" );

// All except the first three divs.
$( "div:gt(2)" );

//:checked pseudo-selector works when used with checkboxes, radio buttons and selects.
$( "form :checked" );

Working with Selectors

$( "h1" ).html( "hello world" );


// Chaining
$( "#content" )
    .find( "h3" )
    .eq( 2 )
    .html( "new text for the third h3!" );


// Creating and adding an element to the page at the same time.
$( "ul" ).append( "<li>list item</li>" );

Traversing

<div class="grandparent">
    <div class="parent">
        <div class="child">
            <span class="subchild"></span>
        </div>
    </div>
    <div class="surrogateParent1"></div>
    <div class="surrogateParent2"></div>
</div>

/* parent */

$( "span.subchild" ).parent();
 // Selecting all the parents of an element that match a given selector:
 
// returns [ div.child, div.parent, div.grandparent ]
$( "span.subchild" ).parents();
 
// returns [ div.child ]
$( "span.subchild" ).closest( "div" );


//Children

// returns [ div.parent, div.surrogateParent1, div.surrogateParent2 ]
$( "div.grandparent" ).children( "div" );
 

- Traversing can be broken down into three basic parts: parents, children, and siblings.

Traversing...


// returns [ div.surrogateParent1 ]
$( "div.parent" ).next();
 
// Selecting a prev sibling of the selectors:
 
// returns [] as No sibling exists before div.parent
$( "div.parent" ).prev();
 
// Selecting all the next siblings of the selector:
 
// returns [ div.surrogateParent1, div.surrogateParent2 ]
$( "div.parent" ).nextAll();
 
// returns [ div.surrogateParent1 ]
$( "div.parent" ).nextAll().first();
 
// Selecting all the previous siblings of the selector:
 
// returns [ div.surrogateParent1, div.parent ]
$( "div.surrogateParent2" ).prevAll();

// Selecting an element's siblings in both directions that matches the given selector:
 
// returns [ div.surrogateParent1, div.surrogateParent2 ]
$( "div.parent" ).siblings();

CSS, styling & Dimentions

// Setting CSS properties.
 
$( "h1" ).css( "fontSize", "100px" ); // Setting an individual property.
 
// Setting multiple properties.
$( "h1" ).css({
    fontSize: "100px",
    color: "red"
});

// Add class
$( "h1" ).addClass( "big" );

//gets width of <h1> element.
$( "h1" ).width();
 
// Sets the height of all <h1> elements.
$( "h1" ).height( "50px" );

Data Methods

// Storing and retrieving data related to an element.
 
$( "#myDiv" ).data( "keyName", { foo: "bar" } );
 
$( "#myDiv" ).data( "keyName" ); // Returns { foo: "bar" }


<div id="dataContainer" data-uid="1" data-name="Bob"></div>

$( "#dataContainer" ).data()
=> {uid: 1, name: 'Bob'}

Utility Methods

var myArray = [ 1, 2, 3, 5 ];
 
if ( $.inArray( 4, myArray ) !== -1 ) {
    console.log( "found it!" );
}
________________________

var firstObject = { foo: "bar", a: "b" };
var secondObject = { foo: "baz" };

var newObject = $.extend( firstObject, secondObject );
 
console.log( firstObject.foo ); // "baz"
console.log( newObject.foo ); // "baz"

var newObject = $.extend( {}, firstObject, secondObject );
 
console.log( firstObject.foo ); // "bar"
console.log( newObject.foo ); // "baz"
_________________________
$.isArray([]); // true
$.isFunction(function() {}); // true
$.isNumeric(3.14); // true
$.type( true ); // "boolean"
$.type( 3 ); // "number"

Iterating

var sum = 0;
var arr = [ 1, 2, 3, 4, 5 ];

$.each( arr, function( index, value ){
    sum += value;
});
 
console.log( sum ); // 15
__________________________________

<ul>
    <li><a href="#" id="a">Link 1</a></li>
    <li><a href="#" id="b">Link 2</a></li>
    <li><a href="#" id="c">Link 3</a></li>
</ul>

$( "li" ).each( function( index, element ){
    console.log( $( this ).text() );
});
// Link1 
// Link2
// LInk3

$( "li" ).map( function( index, element ) {
    return element.id;
}).get();
// Returns [ "a", "b", "c" ]

.index() Function

<ul>
    <div class="test"></div>
    <li id="foo1">foo</li>
    <li id="bar1" class="test">bar</li>
    <li id="baz1">baz</li>
    <div class="test"></div>
</ul>
<div id="last"></div>


var foo = $( "li" );
 
// This implicitly calls .first()
console.log( "Index: " + foo.index( "li" ) ); // 0
console.log( "Index: " + foo.first().index( "li" ) ); // 0
 
var baz = $( "#baz1" );
console.log( "Index: " + baz.index( "li" )); // 2
 
var listItem = $( "#bar1" );
console.log( "Index: " + listItem.index( ".test" ) ); // 1

Questions?

References

  • https://learn.jquery.com
Made with Slides.com