CS-344: WEB ENGINEERING
Dr. Mehdi Hussain mehdi.hussain@seecs.edu.pk
Lecture-9ABC
School of Electrical Engineering and Computer Science (SEECS)
National University of Science and Technology (NUST)
2
Outline
• jQuery
• Downloading and Implementing JQuery
• JQuery Selectors
• JQuery Chain Methods
• JQuery Events
• JQuery Effects
• CSS Implementation
• Callback
• Image Slider
• Traversing
3
jQuery
• A JavaScript library which greatly simplifies JavaScript programming
• jQuery 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.
• Write less, do more!
• Common tasks that require many lines of JavaScript code can be written in few lines.
• Complicated things, like AJAX and DOM manipulation is simplified
• Features
• HTML/DOM manipulation
• CSS manipulation
• HTML event methods
• Effects and animations
• AJAX and other Utilities
4
Installing jQuery
• Download
• http://jquery.com
• For development, use uncompressed file
• E.g., jquery.js , jquery-3.4.1.js
• For deployment, use compressed file
• E.g., jquery-3.4.1.min.js
• For easier upgrades without changing HTML files
• Rename file to jquery.js (or possibly jquery-3.4.1.js)
• Installation
• Load jquery.js before any JS files that use jQuery
• Online API and tutorials
• http://docs.jquery.com
5
Will jQuery work in all browsers?
• The jQuery team knows all about cross-browser issues,
and they have written this knowledge into the jQuery
library
• jQuery will run exactly the same in all major browsers
6
Who Uses jQuery?
Google Amazon IBM
Microsoft Twitter Dell
7
HTML DOM
• A standard way for accessing and manipulating HTML
documents.
• Presents an HTML document as a tree-structure
8
DOM?
• Long story short, the DOM is your html document code.
From the
• <!DOCTYPE> to the </html>
• The DOM is "ready" when everything on the page has
loaded.
• Images
• Stylesheets
• JavaScripts
• jQuery can modify the DOM, but it cannot do so until
the DOM is ready
9
Loading jQuery
• In order to use jQuery you need to load it
• You can include it locally on your own server:
• <script src="/js/jquery.js">
• What if I don’t want to download and host
jQuery locally?
10
jQuery CDN
• If you don't want to download and host jQuery yourself, you
can include it from a CDN (Content Delivery Network).
• Both Google and Microsoft host jQuery
• To use jQuery from Google or Microsoft, use one of the
following:
• <script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jque
ry.min.js"></script>
• <script src=https://ajax.aspnetcdn.com/ajax/jQuery/jquery-
3.3.1.js></script>
Many users already have downloaded jQuery from
Google or Microsoft when visiting another site
11
JQuery Example
• Link to run the code
• Link of odd rows of table
• General Links
12
Wait!!!
• In order to make sure that jQuery can find the element you asked it for,
your browser needs to have loaded it (the DOM needs to be ready)
Q. How can I be sure my code runs at DOM ready?
A. Wrap all your jQuery code with the document ready function:
$(document).ready(function(){
// insert jQuery code here…
});
• Shorthand:
$(function(){
// your jQuery code
});
13
jQuery Syntax
• Tailor made for selecting HTML elements and performing
some action on the element(s)
• With jQuery you select (query) HTML elements and perform "actions" on
them.
• $(selector).action()
• $ sign to define/access jQuery
• (selector) to "query (or find)" HTML elements
• jQuery action() to be performed on the element(s)
14
Lets See an Example!!
Html:
<p>Hello World!</p>
Script:
$(function(){
$("p").addClass("isCool");
});
Resulting html:
<p class="isCool">Hello World!</p>
15
Break It Down Now!
$(function(){// = $(document).ready(function(){
.addClass("isCool
$ ("p")
");
Grabs a DOM element Built in method that adds a
Initiates using a CSS selector. class to the jQuery
the jQuery Collection
function
Selector is in quotes.
Class is in quotes.
Creates a jQuery
$ “Collection”
=
jQuery <p> ends with a semicolon.
16
All Your Basic Selectors Are Belong To Us
• Uses the same syntax you use to style elements in CSS!
$("p") $("div") $("#foo") $(".foo")
id="foo class="
<p> <div>
" foo"
api.jquery.com/category/selectors/
17
Example: Add Class
• jQuery:
$("p").addClass("sophisticated");
• Before:
<p>
• After:
<p class="sophisticated">
18
This <p> Has No Class At All!
• jQuery:
$("p").removeClass("sophisticated");
• Before:
<p class="sophisticated">
• After:
<p class="">
19
<div> Hide and Seek
• jQuery:
$("div").show();
• Before:
<div style="display:none;">
• After:
<div style="display:block;">
20
I’m Not Lame, Am I?
• jQuery:
$("#eric").text("Is Cool");
• Before:
<p id="eric">Is Lame</p>
• After:
<p id="eric">Is Cool</p>
21
JQuery Selectors…
• $(this).hide() - hides the current element.
• $("p").hide() - hides all <p> elements.
• $(".test").hide() - hides all elements with
class="test".
• $("#test").hide() -hides the element with
id="test".
Examples
22
You Can Chain Most Methods Together
$("p")
.addClass("sophisticated").text("Hello World!").show();
Before:
<p style="display:none;">I’m a para</p>
After:
<p class=“sophisticated”
style="display:block;">
Hello World!
</p>
23
Some of Basic Methods
.show() • Show a hidden element
.wrap("<a></a>") • wrap an element with <a>
.parent("p") • Select parent <p>
.html() • Get/Set innerHTML
.val() • Get/Set Value
api.jquery.com/
24
Getters & Setters: Dual Purpose Methods
$("#foo").text();
$("#foo").text("foo");
25
Use jQuery To Get
<p>Eric</p>
$("p").text(); • Output: "Eric"
myVar = $ • Output:
("p").text(); myVar === "Eric"
26
Use jQuery To Set
<p>Eric</p>
$
("p").text("BoBeric") • <p>BoBeric</p>
;
myVar = "BoBeric";
$("p").text(myVar); • <p>BoBeric</p>
27
Basic Selectors
28
Activity
Use the correct selector to hide the element with id="test".
29
Activity
Use the correct selector to hide all elements with class="test".
30
Activity
Use the correct selector to hide all elements in the document.
31
Hierarchical Selectors
33
More Functions
34
Outline
• jQuery
• Downloading and Implementing JQuery
• JQuery Selectors
• JQuery Chain Methods
• JQuery Events
• JQuery Effects
• CSS Implementation
• Callback
• Image Slider
• Traversing
35
jQuery Event
• jQuery is tailor-made to respond to events in an HTML page.
• All the different visitor's actions that a web page can respond to are
called events.
• An event represents the precise moment when something happens
• moving a mouse over an element
• selecting a radio button
• clicking on an element
• The term "fires" is often used with events.
• Example: "The keypress event fires the moment you press a
key".
36
jQuery Event Examples
37
Event Handlers
• Syntax
• $("selector").event( someHandler );
• Example
$("p").click(function(){
alert(“Don’t click me!!”);
});
$("#p1").mouseenter(function(){
alert("You entered p1!");
});
38
Two Ways to Handle Event
$(function() {
$("#alert-button-1").click(showAlert);
});
function showAlert() {
alert("I am live");
}
$(function(){
$("#alert-button-1").click(function() {
alert("I am live");
});
});
39
jQuery Event Examples
• click() // $("p").click(function(){
• dblclick() // $("p").dblclick(function(){
• mouseenter() // $("#p1").mouseenter(function(){
• mouseleave() // $("#p1").mouseleave(function(){
• hover()
/* $("#p1").hover(function(){
alert("You entered p1!");
},
function(){
alert("Bye! You now leave p1!");
}); */
• focus() // $("input").focus(function(){
• on() // $("p").on("click", function(){
• Multiple events
40
Activity
• When we press a keyboard key inside text field element, it
should be hidden. Use the correct event to do so.
41
Outline
• jQuery
• Downloading and Implementing JQuery
• JQuery Selectors
• JQuery Chain Methods
• JQuery Events
• JQuery Effects
• HTML/CSS Implementation
• Callback
• Image Slider
• Traversing
42
jQuery Effects
jQuery has many effects, i.e. Hide, Show, Toggle, Slide,
Fade, and Animate.
Example (How to hide parts of text)
Syntax:
$(selector).hide(speed,callback);
$(selector).show(speed,callback);
• speed= “slow", "fast", or milliseconds
• callback= run after the hide and show executed
• Toggle Example with speed
43
Effect: jQuery Fade
• jQuery has following fade effects, i.e. fadeIn(), fadeOut(),
fadeToggle(), fadeTo().
• Syntax:
$(selector).fadeIn(speed,callback);
$(selector).fadeTo(speed,opacity,callback);
• Example
44
Effect: jQuery Sliding
• jQuery has following sliding effects, i.e. slideDown(),
slideUp(), slideToggle()
• Syntax:
$(selector).slideDown(speed,callback);
$(selector).slideUp(speed,callback);
• Example
• https://
www.w3schools.com/jquery/tryit.asp?filename=tryjquery_slide_toggle
45
Effect: jQuery Animate
Syntax:
$(selector).animate({params},speed,callback);
$(document).ready(function(){
$("button").click(function(){
var div = $("div");
div.animate({left: '100px'}, "slow");
div.animate({fontSize: '3em'}, "slow");
});
});
Example of animate
46
jQuery Stop Effects
Syntax
$(selector).stop(stopAll, goToEnd)
• Example Stop (), Stop with Params
• Other important effects Links
• Chaining Method
$("button").click(function(){
$("#p1").css("color", "red").slideUp(2000).slideDown(2000);
}
48
Outline
• jQuery
• Downloading and Implementing JQuery
• JQuery Selectors
• JQuery Chain Methods
• JQuery Events
• JQuery Effects
• Callback
• HTML/CSS Implementation
• Traversing
• Image Slider (jQuery Image Slider - Quick & Easy)
49
jQuery HTML: Get Content and Attributes
• Get Content - text(), html(), and val()
• text() - Sets or returns the text content of selected elements
• html() - Sets or returns the content of selected elements (including HTML
markup)
• val() - Sets or returns the value of form fields
• Example
• Get/Set Attributes - attr()
• Used to get/set the attribute values of an element
• Get Example
• Set Example
// Get $("#linkTag").attr("href");
// Set $("#linkTag").attr("href", "https://www.nust.edu/seecs.php");
50
jQuery HTML: Add/Remove Elements
With jQuery, it is easy to add/remove new elements /content.
Add Elements
• append() - Inserts content at the end of the selected elements
• prepend() - Inserts content at the beginning of the selected
elements
• after() - Inserts content after the selected elements
• before() - Inserts content before the selected elements
Remove Elements
• remove() - Removes the selected element (and its child elements)
• empty() - Removes the child elements from the selected element
51
jQuery - Get and Set CSS Classes
jQuery has several methods for CSS manipulation. We will look at the
following methods:
• addClass() - Adds one or more classes to the selected
elements
• removeClass() - Removes one or more classes from the selected
elements
• toggleClass() - Toggles between adding/removing classes from
the selected elements
• css() - The css() method sets or returns one or more
style properties for the selected elements.
// css("propertyname");
// css("propertyname“, “value”);
• set multiple css properties
52
Activity: Generate the Output
<body> // CSS Code
<section id=“days">
.highlighted {
<div class=“day"> background-color: #f00;
<p>“Monday"</p> }
</div>
<div class=" day highlighted">
//jQuery
<p>“Tuesday"</p>
</div> $(document).ready(function(){
<div class="day">
<p>“Wednesday"</p> $('#days').on('click', '.day', function() {
</div> $(this).toggleClass('highlighted');
});
<div class="day">
<p>“Thursday"</p> });
</div>
</section>
</body>
53
Activity: Generate the Output
<body> // CSS Code
<section id=“days">
.highlighted {
<div class=“day"> background-color: #f00;
<p>“Monday"</p> }
</div>
<div class=" day highlighted">
//jQuery
<p>“Tuesday"</p>
</div> $(document).ready(function(){
<div class="day">
<p>“Wednesday"</p> $('#days').on('click', '.day', function() {
</div> $(this).toggleClass('highlighted');
});
<div class="day">
<p>“Thursday"</p> });
</div>
</section>
</body>
54
Example HTML Page
<head>
<link rel="stylesheet" type="text/css" href="c10.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="page">
<h1 id="header"></h1>
<h2>Buy groceries</h2>
<ul>
<li id="one" class="hot"><em>fresh</em> figs</li>
<li id="two" class="hot">pine nuts</li>
<li id="three" class="hot">honey</li>
<li id="four">balsamic vinegar</li>
</ul>
</div>
</body>
55
Example HTML Page
<div id="page">
<h1 id="header"></h1>
<h2>Buy groceries</h2>
<ul>
<li id="one" class="hot"><em>fresh</em> figs</li>
<li id="two" class="hot">pine nuts</li>
<li id="three" class="hot">honey</li>
<li id="four">balsamic vinegar</li>
</ul>
</div>
56
Get HTML Fragment
$(function() {
var $listHTML = $('ul').html();
$('ul').append($listHTML);
});
57
Get Text Fragment
$(function() {
var $listText = $('ul').text();
$('ul').append('<p>'+$listText+'</p>');
});
58
Get HTML Node
$(function() {
var $listItemHTML=$('li').html();
$('li').append(
'<i>'+$listItemHTML+'</i>');
});
If we want to access the 2nd list item?
var $listItemHTML=$('li:nth-child(2)').html();
59
Example HTML Page Again
<head>
<link rel="stylesheet" type="text/css" href="c07.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="page">
<h1 id="header"></h1>
<h2>Buy groceries</h2>
<ul>
<li id="one" class="hot"><em>fresh</em> figs</li>
<li id="two" class="hot">pine nuts</li>
<li id="three" class="hot">honey</li>
<li id="four">balsamic vinegar</li>
</ul>
</div>
</body>
60
Changing Content
$(function() {
$('li#one').remove();
$
('li:contains("pine")').text('almonds');
$('li.hot').html(function() {
return '<em>' + $(this).text() +
'</em>'; });
});
61
Adding New Content
$(function() {
$('ul').before(
'<p class="notice">Just updated</p>');
$('li.hot').prepend('+ ');
var $newListItem =
$('<li><em>gluten-free</em>
soy sauce</li>');
$('li:last').after($newListItem);
});
62
Changing CSS
$(function() {
var backgroundColor =
$('li').css('background-color');
$('ul').append(
'<p>Color was: ' + backgroundColor + '</p>');
$('li').css({
'background-color': '#c5a996',
'border': '1px solid #fff',
'color': '#000',
'text-shadow': 'none',
'font-family': 'Georgia',
'padding-left': '+=75'
});
});
64
Basic Effects
$(function() {
var $li = $('li');
$li.hide().each(function(index) {
$(this).delay(700*index)
.fadeIn(700);
});
$li.on('click', function() {
$(this).fadeOut(700);
});
});
65
Traversing
$(function() {
var $h2 = $('h2');
$('ul').hide();
$h2.append(
'<a class="show">show</a>');
$h2.on('click', function() {
$h2.next('ul').fadeIn(500)
.children('.hot')
.addClass('complete');
$h2.find('a').fadeOut();
});
});
66
Traversing CSS
.complete {
background-color: #999;
background-image: url("icon-trash.png");
background-position: right center;
background-repeat: no-repeat;
border-bottom: 1px solid #b0b0b0;
border-top: 1px solid #666;
color: #fff;
text-shadow: 2px 2px 1px #333;
}
69
Outline
• jQuery
• Downloading and Implementing JQuery
• JQuery Selectors
• JQuery Chain Methods
• JQuery Events
• JQuery Effects
• Callback
• HTML/CSS Implementation
• Traversing
• Image Slider (jQuery Image Slider - Quick & Easy)
• Drag and drop Links
70
Further Reading
• http://api.jquery.com
• http://docs.jquery.com
• http://www.w3schools.com/jquery/default.asp