Download presentation
Presentation is loading. Please wait.
1
Introduction to jQuery
CS7026 Introduction to jQuery
2
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.
3
What is jQuery? jQuery's syntax is designed to make it easier to navigate a document, select DOM elements, create animations, handle events, and develop Ajax applications. jQuery also 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 jQuery greatly simplifies JavaScript programming.
4
What is jQuery? jQuery wraps common tasks that normally take many lines of JavaScript 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 Utilities
5
Why jQuery? There are other JavaScript frameworks, but jQuery seems to be the most popular. It is also the most extendable. 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 JavaScript and other JavaScript libraries.
6
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: As the developers have already taken cross-browser issues into account, jQuery will run exactly the same in all major browsers. It is extensible: jQuery can be extended to implement customised behaviour.
7
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
8
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
9
1. 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.
10
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 min.js"></script> </head> Here the downloaded file is in the same directory as the pages where it is being used.
11
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.
12
Including jQuery from a CDN
The following CDNs host jQuery files: jQuery's CDN: To see all available files and versions, visit To use the jQuery CDN, just reference the file directly from the script tag: <script src=" min.js"integrity="sha256- FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
13
Including jQuery from a CDN
The integrity and crossorigin attributes are used for Subresource Integrity (SRI) checking. This allows browsers to ensure that resources hosted on third-party servers have not been tampered with. Use of SRI is recommended as a best-practice, whenever libraries are loaded from a third-party source. Read more at srihash.org
14
Including jQuery from a CDN
Microsoft: The jQuery file can be loaded from Microsoft AJAX CDN. For more details, go to us/aspnet/ajax/cdn/overview#jQuery_Releases_on_the_CDN_0 You will need to put the following code in your page: <script src= " min.js"></script>
15
Including jQuery from a CDN
Google The jQuery file can be loaded from Google CDN. For more details, go to jquery. You will need to put the following code in your page. <script src=" /jquery.min.js"></script>
16
Why Load the JQuery file from a CDN?
Why load the jQuery file from the CDNs rather than your own server? Remember when a browser loads any webpage, it puts related files (eg. JavaScript files, 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.
17
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.
18
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)
19
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()
20
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 });
21
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!"); });
22
jQuery Selectors jQuery 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.
23
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:
24
<!DOCTYPE html> <html> <head> <script src=" 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>
25
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=" min.js"></script> <script src="hide.js"> </script> </head> …
26
jQuery Selectors 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>
27
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>
28
jQuery Selectors – 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")
29
jQuery Selectors – More Examples
Selects the first <li> element of every <ul> $("ul li:first-child") Selects all elements with a href attribute $("[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']")
30
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")
31
Hello World… Let’s have a closer look at a “Hello World” example. We start with an empty html page: <html> <head> <script src=" min.js"></script><script> // we will add our code here </script> </head> <body> <!-- we will add our HTML content here --> </body> </html>
32
Hello World… This page just loads the jquery.js library. 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.
33
Hello World… To do this, we register a ready event for the document:
$(document).ready(function() { // do stuff when DOM is ready });
34
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!"); });
35
Hello World… This should show the alert as soon as you click on the link. In fact it should show the alert as soon as you open any link.
36
Hello World… Let's have a look at what we are doing:
$("a") is a jQuery selector, in this case, it selects all a elements. $ itself is an alias for the jQuery "class", therefore $() constructs a new jQuery object which can then access all the jQuery methods etc. The click() 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.
37
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.
38
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>
39
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"); });
40
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 let’s add some more classes to the child elements of this list.
41
Using Selectors $(document).ready(function() { $("#orderedlist").addClass("red"); }); $("#orderedlist > li").addClass("blue"); }); This selects all child <li>s of the element with the id orderedlist and adds the class .blue from the stylesheet.
42
Using Selectors Now for something a little more sophisticated: We want to add and remove the class when the user hovers over the li element, but only on the last element in the list. $(document).ready(function() { $("#orderedlist").addClass("red"); }); $("#orderedlist > li").addClass("blue"); $("#orderedlist li:last").hover(function() { $(this).addClass("green"); },function(){ $(this).removeClass("green"); });
43
Using Selectors There is more…
$(document).ready(function() { $("#orderedlist").find("li").each(function(i) { $(this).append( " BAM! " + i ); });
44
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.
45
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.
46
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.
47
Using Selectors The [expression] syntax 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", "#e00" ); }); This adds a background colour to all anchor elements with a name attribute.
48
Using Selectors More often than selecting anchors by name, you might need to select anchors by their href attribute. To match only a part of the value, we can use the contains select ("*=") instead of an equals ("="):
49
Using Selectors $(document).ready(function() { $("a[href*='/content/gallery']").click(function() { // do something with all links that point somewhere to /content/gallery });
50
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.
51
Using Selectors $(document).ready(function() { $('#faq').find('dd').hide().end().find('dt').¬ click(function() { $(this).next().slideToggle(); }); Here we use some chaining to reduce the code size and gain better performance, as #faq is only selected once.
52
Using Selectors By using end(), the first find() is undone, so we can start search with the next find() at our #faq element, instead of the dd‘s children. Within the click handler, the function passed to the click() method, we use $(this).next() to find the next sibling starting from the current dt. This allows us to quickly select the answer following the clicked question.
53
Using Selectors In addition to siblings, you can also select parent elements. Maybe you want to highlight the paragraph that is the parent of the link the user hovers. Try this: $(document).ready(function(){ $("a").hover(function(){ $(this).parents("p").addClass("highlight"); },function(){ $(this).parents("p").removeClass("highlight"); }); For all hovered anchor elements, the parent paragraph is searched and a class "highlight" from the CSS added and removed.
54
Using Selectors Lets go one step back before continuing: jQuery is a lot about making code shorter and therefore easier to read and maintain. The following is a shortcut for the $(document).ready(callback)notation: $(function() { // code to execute when the DOM is ready });
55
Using Selectors Applied to the Hello world! example, we end with this:
$(function() { $("a").click(function() { alert("Hello world!"); });
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.