550 likes | 782 Views
CS7026. Introduction to j Query. What is jQuery ?. jQuery is a cross-browser JavaScript Library . A JavaScript library is a library of pre-written JavaScript which allows for easier development of JavaScript-based applications .
E N D
CS7026 Introduction to jQuery
What is jQuery? • jQuery is a cross-browser JavaScript Library. • A JavaScript library is a library of pre-written JavaScript which allows for easier development of JavaScript-based applications. • It was released in January 2006 at BarCamp NYC by John Resig. • It is free, open source software Dual-licensed under the MIT License and the GNU General Public License.
What is jQuery? • jQuery'ssyntax is designed to make it easier to navigate a document, select DOM elements, create animations, handle events, and develop Ajax applications. • jQueryalso provides capabilities for developers to create plug-ins on top of the JavaScript library. • The modular approach to the jQuery library allows the creation of dynamic web pages and web applications. • Essentially jQuerygreatly simplifies JavaScript programming.
What is jQuery? • jQuery takes a lot of common tasks that require many lines of JavaScript code to accomplish, and wraps them into methods that you can call with a single line of code. • The jQuery library contains the following features: • HTML/DOM manipulation • CSS manipulation • HTML event methods • Effects and animations • AJAX • Utilities • In addition, jQuery has plugins for almost any task out there.
Why jQuery? • There are a lots of other JavaScript frameworks out there, but jQuery seems to be the most popular, and also the most extendable. • Many of the biggest companies on the Web use jQuery, such as Google, Microsoft, IBMand Netflix. • It’s easy to use: This is pretty much the main advantage of using JQuery, it is a lot more easy to use compared to standard javaScriptand other javaScriptlibraries.
Why jQuery? • It is fast: Simple and cleaner code, no need to write several lines of codes to achieve complex functionality. It helps to improve the performance of the application • It is cross-browser compatible: jQuerywill run exactly the same in all major browsers, including Internet Explorer 6! • It is extensible:jQuery can be extended to implement customized behaviour.
Why jQuery? • Strong opensource community. • Good documentation and tutorials. • No need to learn fresh new syntaxes to use jQuery, knowing simple JavaScript syntax is enough
Getting Started • There are several ways to start using jQuery on your web site. • You can: • Download the jQuery library from jQuery.com • Include jQuery from a CDN, like Google
Downloading jQuery • There are two versions of jQuery available for downloading: • Production version - this is for your live website because it has been minified and compressed • Development version - this is for testing and development (uncompressed and readable code) • Both versions can be downloaded from jQuery.com.
Including jQuery in your Page • The jQuery library is a single JavaScript file, and you reference it with the HTML <script>tag. • Note that the <script> tag should be inside the <head> section. <head><script src="jquery-1.11.0.min.js"></script></head> • Here the downloaded file is in the same directory as the pages where it is being used.
Including jQuery from a CDN • CDN Stands for Content Distribution Network or Content Delivery Network. • This consists of a large distributed system of servers deployed in multiple data centres. • The goal of a CDN is to serve content to end-users with high availability and high performance. • In a CDN the client accesses a copy of the data nearest to the client location rather than all clients accessing it from one particular server. • This helps to achieve faster data retrieval by the client.
Including jQuery from a CDN • There following CDNs host jQuery files: • jQuery's CDN provided by MaxCDN: • To see all available files and versions, visit http://code.jquery.com • To use the jQuery CDN, just reference the file directly from http://code.jquery.com in the script tag: <script src= "http://code.jquery.com/jquery- 1.11.0.min.js"></script>
Including jQuery from a CDN • Microsoft: • The jQueryfile can be loaded from Microsoft AJAX CDN. For more details, go to http://www.asp.net/ajaxlibrary/cdn.ashx#jQuery_Releases_on_the_CDN_0. • You will need to put the following code in your page: <script src= "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.0.min.js"></script>
Including jQuery from a CDN • Google • The jQueryfile can be loaded from Google CDN. For more details, go to https://developers.google.com/speed/libraries/devguide#jquery. • You will need to put the following code in your page. <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
Why Load the JQuery file from a CDN? • You may ask that if we can load the jQuery file from our own server why load it from the CDNs. • Remember when a browser loads any webpage, it puts related files (eg. Javascriptfiles, CSS files and images) used for that page into its cache. • When the user next browses any web page, the browser loads only those files that are new or modified and are not available in the browser cache. • In this way, the browser improves its performance and loads pages faster.
Why Load the JQuery file from a CDN? • There is a possibility that the user might have already browsed some other web pages that are using the CDN’s jQuery file and that file may already be in the cache. • In this way your page will load faster as the browser will not have to load the jQuery file for your page again.
jQuery Syntax • With jQuery you select (query) HTML elements and perform "actions" on them. • The basic syntax is:$(selector).action() • A $ sign to define/access jQuery • A (selector) to "query (or find)" HTML elements • A jQuery action() to be performed on the element(s)
jQuery Syntax Examples: • hide the current element: $(this).hide() • hide all <p>elements: $("p").hide() • hide all elements with class="test": $(".test").hide() • hide the element with id="test": $("#test").hide()
The Document Ready Event • To ensure that their code runs after the browser finishes loading the document, many JavaScript programmers wrap their code in an onload function: window.onload = function() { alert("welcome"); } • Unfortunately, the code doesn't run until all images are finished downloading (including, say, banner ads). 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() { // Your code here });
The Document Ready Event • For example, inside the ready event, you can add a click handler to the link: $( document ).ready(function() { $("a").click(function( event ) { alert("Thanks for visiting!"); }); });
jQuery Selectors • Query selectors allow you to select and manipulate HTML element(s). • With jQuery selectors you can find elements based on their id, classes, types, attributes, values of attributes and much more. • It's based on the existing CSS Selectors, and in addition, it has some own custom selectors.
jQuery Selectors • All type of selectors in jQuery, start with the dollar sign and parentheses: $(). • The element Selector • The jQuery element selector selects elements based on their tag names. • You can select all <p> elements on a page like this: $("p") • Let’s pause for a moment and put all of this together:
<!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <script> $(document).ready(function(){ $("p").click(function(){ $(this).hide(); }); }); </script> </head> <body> <p>If you click on me, I will disappear.</p> <p>Click me away!</p> <p>Click me too!</p> </body> </html>
Including jQuery in your Page • Note that in practice, it is usually better to place your code in a separate JS file and load it on the page with a <script> element's src attribute. <html> <head> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <script src="hide.js"> </script> </head> …
jQuerySelectors • The #id Selector • Uses the id attribute of a HTML tag to find the specific element. • An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element. • To find an element with a specific id, write a hash character, followed by the id of the element: $("#btnSayHello") This would find <button id="btnSayHello" type="button">Say Hello!</button>
jQuery Selectors • The .class Selector • Finds elements with a specific class. • Write a full stop, followed by the name of the class: $(".btnHideMe") This would find <button class=“btnHideMe" type="button">Hide Me!</button>
jQuerySelectors – More Examples • Selects all elements $("*") • Selects the current HTML element $(this) • Selects all <p> elements with class="intro“ $("p.intro") • Selects the first <p>element $("p:first")
jQuery Selectors – More Examples • Selects the first <li> element of every <ul> $("ulli:first-child") • Selects all elements with a hrefattribute $("[href]") • 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“ $("a[target!='_blank']")
jQuery Selectors – More Examples • Selects all <button> elements and <input> elements of type="button“ $(":button") • Selects all even <tr> elements $("tr:even") • Selects all odd <tr> elements $("tr:odd")
Hello World… • Let’s have a closer look at a “Hello World” example. We start with an empty html page: <html> <head> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script><script> // we will add our code here </script> </head> <body> <!-- we will add our HTML content here --> </body> </html>
Hello World… • This page just loads the jquery.jslibrary. Two comments indicate where we will expand this template with code. • Remember, as almost everything we do when using jQuery reads or manipulates the document object model (DOM), we need to make sure that we start adding events etc. as soon as the DOM is ready.
Hello World… • To do this, we register a ready event for the document: $(document).ready(function() { // do stuff when DOM is ready });
Hello World… • We want to show an alert when clicking a link. So add the following to the <body>: <a href="">Link</a> • Now update the $(document).ready handler: $(document).ready(function() { $("a").click(function() { alert("Hello world!"); }); });
Hello World… • This should show the alert as soon as you click on the link. • In fact it should show the link as soon as you open any link.
Hello World… • Let's have a look at what we are doing: • $("a") is a jQuery selector, in this case, it selects all aelements. • $ itself is an alias for the jQuery "class", therefore $() constructs a new jQuery object which can then access all the jQuery methods etc. • Theclick() function we call next is a method of the jQuery object. It binds a click event to all selected elements (in this case, a single anchor element) and executes the provided function when the event occurs.
Hello World… • This is similar to the following javaScript code: <a href="" onclick="alert('Hello world')">Link</a> • The difference is quite obvious: We don't need to write an onclick for every single element. • We have a clean separation of structure (HTML) and behaviour (JS), just as we separate structure and presentation by using CSS.
Using Selectors • We are going to look at using some more of the selectors we have encountered. • We will look at selecting and modifying the first ordered list in a html page. <ol id="orderedlist"> <li>First element</li> <li>Second element</li> <li>Third element</li> </ol>
Using Selectors • To get started, we want to select the list itself. • The list has an ID "orderedlist". In classic JavaScript, you could select it by using: document.getElementById("orderedlist") • With jQuery, we do it like this: $(document).ready(function() { $("#orderedlist").addClass("red"); });
Using Selectors • The page is linked to a stylesheet (red.css) with a class .red that simply adds a red background. • Therefore, when you reload the page in your browser, you should see that the first ordered list has a red background. The second list is not modified. • Now lets add some more classes to the child elements of this list.
Using Selectors $(document).ready(function() { $("#orderedlist").addClass("red"); }); $("#orderedlist > li").addClass("blue"); }); • This selects all child <li>s of the element with the id orderedlistand adds the class .blue from the stylesheet.
Using Selectors • Now for something a little more sophisticated: We want to add and remove the class when the user hovers the li element, but only on the last element in the list. $(document).ready(function() { $("#orderedlist").addClass("red"); }); $("#orderedlist > li").addClass("blue"); $("#orderedlistli:last").hover(function() { $(this).addClass("green"); },function(){ $(this).removeClass("green"); }); });
Using Selectors • For every onxxxjavaScript event available, like onclick, onchange, onsubmit, there is a jQuery equivalent. • Some other events, like ready and hover, are provided as convenient methods for certain tasks. • You can find a complete list of all events in the jQuery Events Documentation.
Using Selectors • With those selectors and events you can already do a lot of things, but there is more… $(document).ready(function() { $("#orderedlist").find("li").each(function(i) { $(this).append( " BAM! " + (i+1) ); }); });
Using Selectors • find() allows you to further search the descendants of the already selected elements. • Therefore in this case $("#orderedlist").find("li")is the same as $("#orderedlist li"). • each() iterates over every element and allows further processing. • append()is used to append some text to it and set it as text to the end of each element.
Using Selectors • An additional challenge is to select only certain elements from a group of similar or identical ones. • jQuery provides filter() and not() for this. • filter() reduces the selection to the elements that fit the filter expression. • not() does the contrary and removes all elements that fit the expression.
Using Selectors • Think of an unordered list where you want to select all li elements that have no ul children. $(document).ready(function() { $("li").not(":has(ul)").css("border", "1px solid black"); }); • This selects all li elements that have a ul element as a child and removes all elements from the selection. Therefore all li elements get a border, except the one that has a child ul.
Using Selectors • The [expression] syntax is taken from XPath and can be used to filter by attributes. • Maybe you want to select all anchors that have a name attribute: $(document).ready(function() { $("a[name]").css("background", "#eee" ); }); This adds a background colour to all anchor elements with a name attribute.
Using Selectors • More often than selecting anchors by name, you might need to select anchors by their hrefattribute. • To match only a part of the value, we can use the contains select ("*=")instead of an equals ("="):
Using Selectors $(document).ready(function() { $("a[href*='/content/gallery']").click(function() { // do something with all links that point somewhere to /content/gallery }); });
Using Selectors • Until now, all selectors were used to select children or filter the current selection. • There are situations where you need to select the previous or next elements, known as siblings. • Think of a FAQ page, where all answers are hidden first, and shown, when the question is clicked.