Introduction To JQuery
Introduction To JQuery
jQuery
Agenda
▪ What is 'jQuery'?
▪ Launching Code on Document Ready
▪ jQuery Selectors
▪ DOM Manipulation
▪ Event Handling
▪ Effects
▪ Useful Links
What is
'jQuery'?
jQuery: Write Less, Do More
▪ Query is a fast, small, and feature-rich JavaScript library.
▪ It makes things like HTML document traversal and
manipulation, event handling, animation, and Ajax
much simpler with an easy-to-use API that works
across a multitude of browsers.
▪ jQuery is so popular that it often treated as an integral
part of JavaScript but actually it isn't.
Linking jQuery
▪ jQuery is available at official website: http://jQuery.com
▪ You may download jQuery to local folder but it is recommended to use CDN link. There is an official
CDN from jQuery but also there are alternate CDN's from Google, Microsoft and other companies.
▪ jQuery CDN link from http://code.jquery.com:
<script src='//code.jquery.com/jquery-2.1.1.min.js'></script>
▪ Important notes:
– always to link to some specific version of jQuery but not to most recent version without number, as it may break your
project because of future changes;
– to accelerate page load use minified version of the library, you may link to uncompressed library while developing project
to make code debugging possible;
– CDN link shown above does not include protocol, it means that current protocol (http or https) will be used, but it will fail
if html page loads locally, so it is better sometimes to add protocol to link
$ Alias
▪ jQuery uses '$' symbol as alias to object 'jQuery'
▪ This symbol available as a global variable
▪ You may reference library both by '$' alias and 'jQuery' variable
name, but using '$' symbol is much more common and results
in a cleaner and compact code
Basic jQuery Syntax
▪ jQuery syntax is focused on selecting html elements and
performing some actions on the elements
▪ Basic syntax is: $(selector).action()
▪ Comments:
– A $ sign to define/access jQuery
– A (selector) to 'query (or find)' HTML elements
– A jQuery action() to be performed on the element(s)
Launching Code on
Document Ready
window.onload
▪ Very common task in web programming is to run JS code when the browser
finishes loading the document
▪ To achieve this task a developer may attach code to window.onload event:
window.onload = function() {
alert( 'hello' );
}
▪ Unfortunately, the code doesn't run until all images are finished downloading,
including banner ads
jQuery Ready Event
▪ To run code as soon as the document is ready to be
manipulated, jQuery has a statement known as the ready event
$(document).ready(function() {
alert('welcome');
});
$(function() {
alert('welcome');
});
$(document).ready(function() {
$('button').click(function(){
$('div').hide();
});
});
The #id Selector
▪ The jQuery #id selector uses the id attribute of an html tag to find the specific element.
▪ As id should be unique on a page, this selector allows to find a single, unique element.
▪ To select some specific element with id 'demo': $('#demo')
$(document).ready(function() {
$('#someid').click(function(){
$('#demo').hide();
});
});
The .class Selector
▪ The jQuery .class selector uses the class attribute of an html tag to find all elements with this class.
▪ As same class attribute value may be assigned to different elements, this selector allows selecting
multiple elements
▪ To select all elements with class 'demo': $('.demo')
$(document).ready(function() {
$('.someclass').click(function(){
$('.demo').hide();
});
});
CSS Selectors
▪ jQuery allows to use same selectors as used in CSS versions 1-3
▪ Incomplete list of some popular selectors:
– 'X + Y': adjacent selector, select only the element that is immediately preceded by the former element;
– 'X > Y': selects direct children of an element;
– 'X ~ Y': sibling combinator, similar to 'X + Y' but allows selection of element 'Y' even if it is not immediately follows
'X' but just follows it;
– 'X[title]': attribute selector, selects element 'X' if it has attribute 'title';
– 'X[title=value]': attribute value selector, selects element 'X' if it has attribute 'title' with value 'value'
▪ Selector separated by comma treated as combination of selectors, selectors separated by space
matched against descendants
▪ For complete list of selectors see jQuery manual: http://api.jquery.com/category/selectors/
DOM Manipulation
Introduction to DOM Manipulation with jQuery
▪ jQuery allows to read, add or remove information about class for any element. This may be
useful to change how elements shown based on predefined CSS styles assigned to the class and
much more
▪ These methods are:
– .addClass() – adds class:
$('p').addClass('myClass');
– .removeClass() – removes class:
$('p').removeClass('myClass');
– .hasClass() – checks if class is assigned:
$('#myp').hasClass('myClass');
– .toggleClass() – adds class if it is not assigned and vice versa: $('#myp').toggleClass('myClass');
▪ These methods, like other methods of jQuery may be chained to each other:
$('p').removeClass('myClass noClass').addClass('yourClass');
Reading and Changing Styles
▪ jQuery provides method .css() that allows to read or set style data.
▪ If this method used as getter, it returns CSS property value of a first element that matches
selector.
Syntax: .css('propertyName')
Sample: var color = $('#myDiv').css('background-color');
▪ If this method used as setter, it sets CSS property values for all elements that match selector.
Syntax:
– .css(propertyName, value); // value - a value to set for the property
– .css(propertyName, function); // function - a function returning
// the value to set
– .css(properties); // properties - an object of
// property-value pairs to set
jQuery Event Handling
jQuery Event Basics
▪ It is very convenient to use jQuery to set up event-driven responses
on page elements.
▪ These events are often triggered by the end user's interaction with
the page, such as when text is entered into a form element or the
mouse pointer is moved.
▪ In some cases, such as the page load and unload events, the browser
itself will trigger the event.
▪ jQuery offers convenience methods for most native browser events.
These methods are — including .click(), .focus(), .blur(), .change(), etc.
Setting Up Browser onclick Event
▪ Next example setups onclick event handler for all
paragraphs on a page:
▪ Using .on() method we may setup any native browser event as well as custom
events:
$( 'p' ).on( 'click', function() {
console.log( 'click' );
});
▪ Or multiple events:
$( 'input' ).on('click change', // bind listeners for multiple events
function() {
console.log( 'An input was clicked or changed!' )
}
);
Using Different Handlers for Multiple Events
▪ In the example below shown how to use different event
handlers for multiple events:
▪ jQuery can also let you change a content's visibility based on its current visibility state.
Method .toggle() will show content that is currently hidden and hide content that is
currently visible. You can pass the same arguments to .toggle() as you pass to any of
the effects methods above.
// Instantaneously toggle the display of all paragraphs
$( 'p' ).toggle();
// Slowly toggle the display of all images
$( 'img' ).toggle( 'slow' );
▪ There are also .slideToggle() and .fadeToggle() methods:
// Toggle the display of all ordered lists over 1 second using slide up/down
$( 'ol' ).slideToggle( 1000 );
// Toggle the display of all blockquotes over 0.4 seconds using fade in/out
$( 'blockquote' ).fadeToggle( 400 );
Doing Something After an Animation
Completes
▪ If we want to do something after animation completes, we can't use such code
because it won't wait for completion:
// Incorrect: Fade in all hidden paragraphs; then add a style class to them
$( 'p.hidden' ).fadeIn( 750 ).addClass( 'lookAtMe' );
▪ To defer an action until after an animation has run to completion, you need to use
an animation callback function. You can specify your animation callback as the
second argument passed to any of the animation methods discussed above. For the
code snippet above, we can implement a callback as follows:
// Fade in all hidden paragraphs; then add a style class to them
$( 'p.hidden' ).fadeIn( 750, function() {
// this = DOM element which has just finished being animated
$( this ).addClass( 'lookAtMe' );
});
Useful links
Links
▪ Official jQuery Website: http://jquery.com/
▪ Official jQuery Learning Center: http://learn.jquery.com/
▪ w3schools.com jQuery Tutorial: http://www.w3schools.com/jquery/
Thank you!