SlideShare a Scribd company logo
UNIT I
Java Script and jQuery
Contents
Query and JavaScript Syntax – Understanding and Using JavaScript
Objects - Accessing DOM Elements Using JavaScript and jQuery
Objects – Navigating and Manipulating jQuery Objects and DOM
Elements with jQuery – Applying JavaScript and jQuery Events for
Richly Interactive Web Pages.
Query and JavaScript Syntax
1. Adding jQuery and JavaScript to a Web Page
2. Accessing the DOM
3. Understanding JavaScript Syntax
What is jQuery?
● jQuery is a lightweight, "write less, do more", JavaScript library.
● jQuery greatly simplifies JavaScript programming.
● The purpose of jQuery is to make it much easier to use JavaScript on your website.
● 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.
● jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX calls and
DOM manipulation.
The jQuery library contains the following features:
● HTML/DOM manipulation
● CSS manipulation
● HTML event methods
● Effects and animations
● AJAX
● Utilities
Why jQuery?
There are lots of other JavaScript libraries out there, but jQuery is probably the most
popular, and also the most extendable.
Many of the biggest companies on the Web use jQuery, such as:
● Google
● Microsoft
● IBM
● Netflix
1.Adding jQuery and JavaScript to a Web Page
Loading the jQuery Library
<script> tag is used to load the jQuery into your web page.
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
● In the following statements, The first loads it from the jQuery CDN
source and the second loads it from the web server
○ <script src="http://code.jquery.com/jquery-latest.min.js"></script>
○ <script src="includes/js/jquery-latest.min.js"></script>
Implementing Your Own jQuery and JavaScript
● A pair of <script> statements that load jQuery and then use it.
● The document.write() function just writes text directly to the browser to be
rendered:
<script src="http://code.jquery.com/jquery-latest.min.js">
</script>
<script>
function writeIt(){
document.write("jQuery Version " + $().jquery + "
loaded.");
}
</script>
Accessing HTML Event Handlers
● Each supported event is an attribute of the object that is receiving the
event.
● If you set the attribute value to a JavaScript function, the browser will
execute your function when the event is triggered.
<!DOCTYPE html>
<html>
<head>
<title>jQuery Version</title>
<meta charset="utf-8" />
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
function writeIt(){
document.write("jQuery Version " + $().jquery +" loaded.");
}
</script>
</head>
<body onload="writeIt()">
</body>
</html>
2.Accessing the DOM
Using Traditional JavaScript to Access the DOM
● Traditionally, JavaScript uses the global document object to access
elements in the web page.
● The simplest method of accessing an element is to directly refer to it by
id with help of getElementById() function
● Another helpful JavaScript function is getElementsByTagName() which
is used to access the DOM elements
● This returns a JavaScript array of DOM elements that match the tag
name.
Example
<!DOCTYPE html>
<html>
<body>
<h1 id="demo"></h1>
<script>
document.getElementById("demo").innerHTML ="welcome"
</script>
</body>
</html>
Using jQuery Selectors to Access HTML Elements
● Accessing HTML elements is one of jQuery’s biggest strengths.
● jQuery uses selectors that are very similar to CSS selectors to access one or more
elements in the DOM;
● Query selectors are used to select and manipulate HTML element(s).
● jQuery selectors are used to "find" (or select) HTML elements based on their name, id,
classes, types, attributes, values of attributes and much more
● All selectors in jQuery start with the dollar sign and parentheses: $().
○ Element selector
○ #id selector
○ .class selector
Element selector
● The jQuery element selector selects elements based on the element name.(example:$("p"))
● Example:
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").css("color", "red");
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<button>change color</button>
</body>
</html>
#id selector
● The jQuery #id selector uses the id attribute of an HTML tag to find the specific
element.(example:$("#test"))
● Example:
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#p1").css("background-color", "yellow");
});
});
</script>
</head>
<body>
<p id="p1">welcome</p>
<button>change color</button>
</body>
</html>
Class selector
● The jQuery .class selector finds elements with a specific class.(example:$(".test"))
● Example:
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function(){
$(".test").css({"background-color": "yellow", "font-size": "200%"});
});
</script>
</head>
<body>
<p class="test">Welcome</p>
</body></html>
3.Understanding JavaScript Syntax
Creating Variables
● Variables are containers for storing data and access data from your
JavaScript files.
● Variables can point to simple data types, such as numbers or strings, or
they can point to more complex data types, such as objects.
● var keyword is used to define a variable in JavaScript
● Example:
○ var myString = "Some Text";
Understanding JavaScript Data Types
● String—Stores character data as a string.
○ The character data is specified by either single or double quotes.
○ var myString = 'Some Text';
○ var anotherString = "Some Other Text";
● Number—Stores the data as a numerical value
○ Example
■ var myInteger = 1;
■ var cost = 1.33;
● Boolean—Stores a single bit that is either true or false.
○ Booleans are often used for flags.
○ var yes = true;
○ var no = false;
● Array—An indexed array is a series of separate distinct data items all stored under a
single variable name
○ var arr = ["one", "two", "three"]
○ var first = arr[0];
● Associative Array/Objects
○ An associative array is an array with string keys rather than numeric keys. Associative arrays
are dynamic objects that the user redefines as needed.
○ var obj = {"name":"Brad", "occupation":"Hacker", "age","Unknown"};
○ var name = obj.name;
Using Operators
● Arithmetic Operators(=,+,-,/,*,+=,-=,*=,/=,%=)
● Comparison Operators(==,!=,>,>=,<,<=,===,!=,&&,!!,!)
Conditional statements
● if statement
● if-else statement
● Nested if statement
● Switch case
Looping statements
● while loops
● do while loops
● for loops
● for in loops
Creating functions
● Defining Functions
○ Functions are defined using the keyword function followed by a function name that
describes the use of the function, list of zero or more arguments in () parentheses, and a
block of one or more code statements in {} brackets.
● Passing Variables to Functions
● Returning Values from Functions
Example:
<html>
<head>
<script type="text/javascript">
var a=10,b=20;
function add(a,b)
{
c=a+b;
return c;
}
document.write("the result is"+add(a,b));
</script>
</head>
<body>
</body>
</html>
Understanding Variable Scope
● Each identifier in a program also has a scope.
● Global variables or script-level variables that are declared in the head element are
accessible in any part of a script and are said to have global scope
● Identifiers declared inside a function have function (or local) scope and can be
used only in that function.
● If a local variable in a function has the same name as a global variable, the global
variable is “hidden” from the body of the function.
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>scope</title>
<script>
var x = 1;// global scope
function start()
{
functionA();
functionB();
functionA();
functionB();
}
function functionA()
{
var x = 25;//local scope
document.writeln("the value of x is"+x+"<br>");
x++;
document.writeln("the value of x is"+x+"<br>");
}
function functionB()
{
document.writeln("the value of x is"+x+"<br>");
x = x*10;
document.writeln("the value of x is"+x+"<br>");
}
start();
</script>
</head><body>
</body>
</html>
Adding Error Handling
● The try statement defines a code block to run (to try).
● The catch statement defines a code block to handle any error.
● The finally statement defines a code block to run regardless of the result.
● The throw statement defines a custom error.
Example
<html>
<body>
<script>
function sqrRoot(x)
{
try
{
if(isNaN(x)) throw "Can't Square Root Strings";
if(x>0)
return "sqrt= " + Math.sqrt(x);
}
catch(err)
{
return err;
}
}
function writeIt()
{
document.write(sqrRoot("four") + "<br>");
document.write(sqrRoot(4) + "<br>");
}
writeIt();
</script></body></html>
Understanding and Using JavaScript Objects
1. Using object syntax
2. Understanding Built-in Objects
3. Creating Custom-Defined Objects
1.Using object syntax
Object
● An object is really a container to group multiple values and, in some instances, functions
together.
● The values of an object are called properties, and functions are called methods.
Creating a New Object Instance
● Object instances are created using the new keyword with the object constructor name.
For example, to create a Number object, you use the following line of code:
○ var x = new Number("5");
Accessing Object Properties
● All JavaScript objects have values that are accessible via a standard dot-naming syntax.
● For example, consider an object with the variable name user that contains a property
firstName.
○ user.FirstName
Accessing Object Methods
● An object method is a function that is attached to the object as a name. The function can
be called by using the dot syntax to reference the method name
○ user.getFullName()
2.Understanding Built-in Objects
Number
● The Number object provides functionality that is useful when dealing
with numbers.
● var x = new Number("5.55555555");
Example:
<html>
<body>
<h2>JavaScript Number Methods</h2>
<script>
var x = 9.656;
document.write(x.toExponential()+"<br>");
document.write(x.toFixed(2)+"<br>");
document.write(x.toPrecision(6)+"<br>");
document.write(x.valueOf());
</script>
</body></html>
String
● JavaScript automatically creates a String object anytime you define a
variable that has a string data type
● var myStr = "Welcome";
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<script>
var text = "HELLO WORLD";
var text1 = "sea";
var text2 = "food";
let text3 = "Hello planet earth, you are a great planet";
var letter = text.charAt(0);
document.write(letter+"<br>");
var code = text.charCodeAt(0);
document.write(code+"<br>");
var result = text1.concat(text2);
document.write(result+"<br>");
var mytext = String.fromCharCode(65);
document.write(mytext+"<br>");
let r = text3.indexOf("planet");
document.write(r+"<br>");
let r1 = text3.lastIndexOf("planet");
document.write(r1);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<script>
let text = "The rain in SPAIN stays mainly in the plain";
let result = text.match(/rain/);
document.write(result+"<br>");
document.write(text.replace("SPAIN", "London")+"<br>");
document.write(text.search("rain")+"<br>");
document.write(text.slice(0,5)+"<br>");
document.write(text.split(" ",3)+"<br>");
document.write(text.substr(4, 3)+"<br>");
document.write(text.substring(1, 4));
</script>
</body>
</html>
Array
● The Array object provides a means of storing and handling a set of other objects.
Arrays can store numbers, strings, or other JavaScript
var arr = ["one", "two", "three"];
Example:
<html>
<body>
<h1>JavaScript Arrays</h1>
<script>
const arr1 = ["apple", "banana"];
const arr2 = ["orange", "grapes", "Lemon","orange"];
const children = arr1.concat(arr2);
document.write(children+"<br>");
document.write(arr2.indexOf("Lemon")+"<br>");
document.write(arr2.join(" & ")+"<br>");
document.write(arr2.lastIndexOf("orange")+"<br>");
document.write(arr2.pop()+"<br>");
document.write(arr2+"<br>");
arr2.push("Mango");
document.write(arr2+"<br>");
document.write(arr2.reverse());
</script>
</body>
<html>
<body>
<h1>JavaScript Arrays</h1>
<script>
const arr2 = ["orange", "grapes", "Lemon","orange"];
document.write(arr2.shift()+"<br>");
document.write(arr2+"<br>");
document.write(arr2.slice(0, 2)+"<br>");
arr2.splice(2, 1, "mango", "Kiwi")
document.write(arr2+"<br>");
arr2.splice(2, 2);
document.write(arr2+"<br>");
arr2.unshift("apple", "Pineapple");
document.write(arr2+"<br>");
document.write(arr2.sort());
</script>
</body>
</html>
Date
The Date object provides access to the current time on the browser’s
system
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Dates</h1>
<script>
const d = new Date();
document.write(d)
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>Date Object Methods</title>
<script type="text/javascript">
var current = new Date();
document.write("<h1>String representations and valueOf</h1>");
document.write("<br>toString:"+current.toString());
document.write("<br>toLocaleString:"+current.toLocaleString());
document.write("<br>toUTCString:"+current.toUTCString());
document.write("<br>valueOf:"+current.valueOf());
document.write("<h1>Get methods for local time zone</h1>");
document.write("<br>getDate:"+current.getDate());
document.write("<br>getDay:"+current.getDay());
document.write("<br>getMonth:"+current.getMonth());
document.write("<br>getFullYear:"+current.getFullYear());
document.write("<br>getTime:"+current.getTime());
document.write("<br>getHours:"+current.getHours());
document.write("<br>getMinutes:"+current.getMinutes());
document.write("<br>getSeconds:"+current.getSeconds());
document.write("<br>getMilliseconds:"+current.getMilliseconds());
document.write("<br>getTimezoneOffset:"+current.getTimezoneOffset());
document.write("<h1>Specifying arguments for a new Date</h1>");
var anotherDate = new Date( 2021, 3, 18, 1, 5, 0, 0 );
document.write(anotherDate);
</script>
<body>
</body>
</html>
Math
The Math object is really an interface to a mathematical library that provides a
ton of time-saving functionality
<!DOCTYPE html>
<html>
<head>
<title> math object</title>
<meta charset="UTF-8">
<script type="text/javascript">
var result = Math.sqrt( 900 );
document.write(result);
</script>
<body>
</body></html>
Math Object Methods
RegExp
● When dynamically processing user input or even data coming back
from the web server, an important tool is regular expressions.
● Regular expressions allow you to quickly match patterns in text and
then act on those patterns.
● var re =/pattern/modifiers;
● Available modifiers in JavaScript
i—Perform matching that is not case sensitive.
g—Perform a global match on all instances rather than just the
first.
m—Perform multiline match
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Regular Expressions</h2>
<script>
var myStr = "Teach Yourself jQuery & JavaScript in 24 Lessons";
var re = /yourself/i;
var newStr = myStr.replace(re, "Your Friends");
document.write(newStr);
</script>
</body>
</html>
3.Creating Custom-Defined Objects
● Objects are variables too. But objects can contain many values.
● Object values are written as name : value pairs (name and value separated by a
colon).
● var user = new Object();
○ user.first="Brad";
○ user.last="Dayley";
● var user = {'first':'Brad','last':'Dayley'};
● document.write(user.first + " " + user.last);
Adding Methods to JavaScript Objects
<html>
<body>
<h2>JavaScript Objects</h2>
<script>
var user = new Object();
user.first="abi";
user.last="karthi";
user.getFullName = makeFullName;
var user2 = {
'first':'john',
'last':'David',
'getFullName':makeFullName
};
function makeFullName()
{
return this.first + " " + this.last;
}
var user3 = {
first: "John",
last: "Peter",
getFullName : function() {
return this.first + " " + this.last;
}
};
document.write(user.getFullName()+"<br>");
document.write(user2.getFullName()+"<br>");
document.write(user3.getFullName());
</script>
</body>
</html>
Using a Prototyping Object Pattern→ The prototyping pattern is implemented
by defining the functions inside the prototype attribute of the object instead of the
object itself.
<html>
<body>
<h1> Using a Prototyping Object Pattern </h1>
<script>
function User(first, last){
this.first = first;
this.last = last;
}
User.prototype = {
getFullName: function(){
return this.first + " " + this.last;
}
};
var user1 = new User("John", "Peter");
document.write(user1.getFullName());
</script>
</body>
</html>
Accessing DOM Elements Using JavaScript and jQuery
Objects
1. Understanding DOM Objects Versus jQuery Objects
2. Accessing DOM Objects from JavaScript
3. Using jQuery Selectors
1.Understanding DOM Objects Versus jQuery Objects
Javascript DOM objects
● In a web page, DOM (Document Object Model) objects refer to the objects that
represent the elements in the page's HTML source code.
● These objects can be manipulated using JavaScript, and can be accessed and modified
using the DOM API (Application Programming Interface).
● The DOM API provides a number of functions and properties that allow you to access
and modify DOM objects.
● For example, you can use the getElementById function to get a reference to an
element with a specific id, or you can use the innerHTML property to get or set the
HTML content of an element.
Drawbacks
● Complexity: The DOM API can be complex to work with, as it requires you to navigate the
hierarchical structure of the DOM and access elements using a variety of functions and
properties.
● Browser compatibility: The DOM API can vary between different browsers, which can make it
more challenging to write code that works consistently across different browsers.
● Performance: Modifying the DOM can be computationally intensive, as it requires the browser
to update the layout and rendering of the page.
These challenges can be mitigated to some extent by using tools such as the jQuery library, which
provides a more consistent and convenient interface for working with DOM objects.
list of some of the important attributes and methods of DOM objects
Example:(click())
<!DOCTYPE html>
<html>
<body>
<h2>The click() Method</h2>
<form>
<input type="checkbox" id="myCheck" onmouseover="myFunction()">click me
</form>
<script>
function myFunction() {
document.getElementById("myCheck").click();
}
</script>
</body>
</html>
Example:(parent and child node)
<html>
<body>
<h2>The parentNode and child node Property</h2>
<ul id="u1">
<li id="myLI">Coffee</li>
<li>Tea</li>
</ul>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
let name = document.getElementById("myLI").parentNode.nodeName;
document.getElementById("demo").innerHTML = "parent node is "+name;
const nodeList = document.getElementById("u1").children;
document.getElementById("demo1").innerHTML =nodeList.length;
const nodeList1 = document.getElementById("u1").childNodes;
document.getElementById("demo2").innerHTML =nodeList1.length;
</script>
</body>
</html>
Example:(outerhtml)
<html>
<body>
<h2>The outerHTML Property</h2>
<p id="myP">I am a paragraph! Click "Change" to replace me with a header.</p>
<button onclick="myFunction()">Change</button>
<script>
function myFunction() {
const element = document.getElementById("myP");
element.outerHTML = "<h2>This is a h2 element.</h2>";
}
</script>
</body>
</html>
Example:(getattribute)
<html>
<head>
<style>
.democlass {
color: red;
}
</style>
<script>
function myFunction() {
var x = document.getElementById("a").getAttribute("class");
document.getElementById("demo").innerHTML = x;
}
</script>
</head>
<body>
<h1 id="a" class="democlass">Hello World</h1>
<input type="submit" value="click to get the attribute" onclick="myFunction()">
<p id="demo"></p>
</body>
</html>
Example:(setattribute)
<html>
<head>
<style>
.democlass {
color: red;
}
</style>
<script>
function myFunction() {
var x = document.getElementById("a").setAttribute("class", "democlass");
}
</script>
</head>
<body>
<h1 id="a">Hello World</h1>
<input type="submit" value="click to set attribute" onclick="myFunction()">
</body>
</html>
Example:(appendchild)
<html>
<body>
<p id="p2">This is another paragraph.</p>
<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);
var element = document.getElementById("p2");
element.appendChild(para);
</script>
</body>
</html>
jQuery Objects
● jQuery objects are basically wrapper objects around a set of DOM elements.
● jQuery objects are objects created by the jQuery library, which is a JavaScript
library for simplifying HTML document traversal, event handling, and animating.
● jQuery objects are collections of DOM (Document Object Model) elements that can be
manipulated using the functions and methods provided by the jQuery library.
● Query objects are designed to be more convenient to work with than DOM objects, as
they provide a simpler and more consistent interface for manipulating elements in the
page.
Advantages
● Simplicity: jQuery objects provide a simple and consistent interface for interacting
with DOM elements, which can make it easier to write and maintain code that
manipulates these elements.
● Browser compatibility: jQuery objects abstract away many of the differences between
different browsers, which can make it easier to write code that works consistently
across different browsers.
● Convenience: jQuery objects provide a wide range of functions and methods for
manipulating DOM elements, which can make it easier to perform common tasks such as
selecting elements, modifying their attributes or styles, or handling events.
● Performance: jQuery is designed to be efficient and fast, and can often perform tasks
such as DOM manipulation more quickly than equivalent code using the DOM API.
List of some of the important methods of jQuery objects
Example:(html())
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").html("Hello <b>world!</b>");
});
});
</script>
</head>
<body>
<button>Change content of all p elements</button>
<p> </p>
<p> replace me </p>
</body></html>
Example:(val() and attr())
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("img").attr("width", "500");
$("input:text").val("KEC");
});
});
</script>
</head>
<body>
<img src="img_pulpitrock.jpg" alt="Pulpit Rock"><br>
<p>Name: <input type="text" name="user"></p>
<button>click</button>
</body>
</html>
Example:(addclass(), css())
<html><head>
<style>
.intro {
font-size: 150%;
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#p1").css("background-color", "yellow");
$("p").addClass("intro");
});
});
</script></head>
<body>
<p id="p1">welcome</p>
<button>change color</button>
</body>
</html>
Example:(height(),width(),hide())
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").height(200);
$("div").width(200);
$("h1").hide();
});
});
</script>
</head>
<body>
<div style="background-color:lightblue;"></div><br>
<h1> welcome </h1>
<button>click</button>
</body>
</html>
2.Accessing DOM Objects from JavaScript
Finding DOM Objects by ID
● The simplest is to find an HTML element using the value of the id
attribute using the getElementById(id) function.
● getElementById(id) searches the DOM for an object with a atching id
attribute.
Example:
<html>
<body>
<h2>The getElementById() Method</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello World";
</script>
</body>
</html>
Finding DOM Objects by Class Name
The getElementsByClassName() method returns a collection of child elements with
a given class name.
<html>
<body>
<h2>The getElementsByClassName() Method</h2>
<div class="example">Element1</div>
<div class="example">Element2</div>
<script>
collection = document.getElementsByClassName("example");
collection[0].innerHTML = "Hello World!";
</script>
</body>
</html>
Finding DOM Objects by Tag Name
● Another way to search for HTML elements is by their HTML tag, using the
getElementsByTagName(tag).
● This function returns a list of DOM objects with matching HTML tags
<html>
<body>
<h2>The getElementsByTagName() Method</h2>
<p>This is a paragraph.</p>
<script>
document.getElementsByTagName("p")[0].innerHTML = "Hello World!";
</script>
</body>
</html>
3.Using jQuery Selectors
● Applying Basic Selectors
● Applying Attribute Selectors
● Applying Content Selectors
● Applying Hierarchy Selectors
● Applying Form Selectors
● Applying Visibility Selectors
● Applying Filtered Selectors
Applying Basic Selectors
● The most commonly used selectors are the basic ones.
● The basic selectors focus on the id attribute, class attribute, and tag
name of HTML elements
Class selector
● The jQuery .class selector finds elements with a specific class.(example:$(".test"))
● Example:
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function(){
$(".test").css({"background-color": "yellow", "font-size": "200%"});
});
</script>
</head>
<body>
<p class="test">Welcome</p>
</body></html>
#id selector
● The jQuery #id selector uses the id attribute of an HTML tag to find the specific
element.(example:$("#test"))
● Example:
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#p1").css("background-color", "yellow");
});
});
</script>
</head>
<body>
<p id="p1">welcome</p>
<button>change color</button>
</body>
</html>
Element selector
● The jQuery element selector selects elements based on the element name.(example:$("p"))
● Example:
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").css("color", "red");
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<button>change color</button>
</body>
</html>
Applying Attribute Selectors
● Another way to use jQuery selectors is to select HTML elements by their attribute
values
● Attribute values are denoted in the selector syntax by being enclosed in [] brackets
Example:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function(){
$("[id=choose]").css("background-color", "yellow");
$("h1[class*=Content]").css("background-color", "green");
$("p[id][class$=menu]").css("background-color", "red");
});
</script>
</head>
<body>
<h1 class="leftContent">Welcome to</h1>
<h1 class="rightContent">Fruit shop</h1>
Who is your favourite fruit:
<ul id="choose">
<li>Apple</li>
<li>Orange</li>
<li>banana</li>
</ul>
<p id="m" class="menu"> Thank you </p>
<p id="m1" class="menu1"> visit again </p>
</body>
</html>
Applying Content Selectors
● Another set of useful jQuery selectors are the content filter selectors.
● These selectors are used to select HTML elements based on the content inside
the HTML element
Example:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function(){
$("p:contains(are)").css("background-color", "yellow");
$("div:has(span)").css("background-color", "red");
$("h1:parent").css("background-color", "blue");
});
</script>
</head>
<body>
<h1>Welcome to the shop</h1>
<p>The list of fruits are</p>
<ul>
<li>Apple</li>
<li>Banana</li>
</ul>
<div>choose your <span>favorite </span></div>
</body>
</html>
Applying Hierarchy Selectors
● An important set of jQuery selectors are the hierarchy selectors.
● These selectors are used to select HTML elements based on the DOM hierarchy.
Example:
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function(){
$("div span").css("background-color", "yellow");
$("div.menu > span").css("background-color", "red");
$("label+input.item").css("background-color", "blue");
$("#menu ~ div").css("background-color", "green");
});
</script>
</head>
<body>
<div><h1>Welocme to <span>KEC </span>Engg College</p></div>
<div class="menu"> PG Department:<span> MSC(SS)</span> </div>
<form>
<label>search:</label>
<input type="text" class="item">
</form>
<div> Other departments are </div>
<ul id="menu">
<li> CSE </li>
<li>IT </li></ul>
<div> Thank you!!! </div>
<div> visit again </div>
</ul></body></html>
Applying Form Selectors
● An extremely useful set of selectors when working with dynamic HTML forms are
the form jQuery selectors.
● These selectors are used to select elements in the form based on the state of the
form element
Example:
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function(){
$("input:checked").wrap("<span style='background-color:red'></span>");
$(":selected").css("background-color", "orange");
$("input").focus();
$(":focus").css("background-color", "yellow");
$(":disabled").css("background-color","red");
});
</script></head>
<body>
<form>
Choose your favorite color
<input type="checkbox" checked="checked">Red
<input type="checkbox">Green<br>
select fruits:
<select>
<option>Apple</option>
<option selected="selected">Orange</option>
<option>Mango</option>
<option>Banana</option>
</select>
Search:<input type="text" /><br><br>
Give feedback:<br>
<textarea disabled="disabled"> </textarea>
</form>
</body></html>
Applying Visibility Selectors
● The visibility selectors are used to to control the flow and interactions of the
web page components and it selects the HTML elements that are hidden or visible
Example:
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function(){
$("p:visible").css("background-color", "yellow");
$("h2:visible").css({"visibility":"visible","color":"red"});
$("p:hidden").show(3500);
});
</script>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a pargraph.</p>
<p>This is another paragraph.</p>
<h2 style="visibility:hidden;">This is a hidden paragraph.</h2>
<p style="display:none;">This is a hidden paragraph that is slowly shown.</p>
</body>
</html>
Applying Filtered Selectors
● Filtered selectors append a filter on the end of the selector statement that limits
the results returned by the selector
Example:
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function(){
$("li:odd").css("background-color", "orange");
$("li:even").css("background-color", "pink");
$("li:gt(1)").css("color", "white");
$("li:lt(2)").css("color", "red");
$("div:eq(1)").css("background-color", "yellow");
$("div:first").css("background-color", "green");
$(":header").css("color", "red"); });</script></head>
<body>
<h1> Welcome to the shop </h1>
<div> select the fruits </div>
<ul>
<li>Apple </li>
<li>Orange </li>
<li>banana </li>
<li>grape </li>
</ul>
<div> Thank you </div>
</body>
</html>
Navigating and Manipulating jQuery Objects and DOM Elements with
jQuery
1. Chaining jQuery Object Operations
2. Filtering the jQuery Object Results
3. Traversing the DOM Using jQuery Objects
4. Looking at Some Additional jQuery Object Methods
1.Chaining jQuery Object Operations
Chaining allows us to run multiple jQuery methods (on the same element)
within a single statement.
Advantages:
While using method chaining in jQuery, it ensures that there is no need
to use the same selector more than once
Example:
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#p1").css("color", "red").slideUp(2000).slideDown(2000);
});
});
</script>
</head>
<body>
<p id="p1">jQuery programs</p>
<button>Click me</button>
</body>
</html>
2.Filtering the jQuery Object Results
● jQuery objects provide a good set of methods which are used to alter
the DOM objects represented in the query.
Example:
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function(){
$("p").filter(".intro").css("background-color", "yellow");
$("p").eq(2).css("background-color", "red");
$("li").first().css("color", "red");
$("li").last().css("color", "green");
$("h1").has("span").css("color", "blue");
$(".menu").not("span").css("color", "orange");
$("p").slice(1,3).css("font-size", "20px");
});</script></head>
<body>
<h1>Welcome to <span class="menu">My College</span></h1>
<h1 class="menu">Departments</h1>
<p>BSC</p>
<p class="intro">MSC</p>
<p>CSE</p>
<p>IT</p>
<h1>Programming languages to learn</h1>
<ul>
<li>C</li>
<li>C++</li>
<li>JAVA</li>
</ul></body></html>
3.Traversing the DOM Using jQuery Objects
● Another important set of methods attached to the jQuery object are
the DOM traversing methods.
● DOM traversal is used to select elements based on their relationship to
other elements.
● The DOM is referred to as the DOM tree because it is organized in a
tree structure, with the document as the root and nodes that can have
both parents, siblings, and children.
Example:
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function(){
$("div").children("p").css({"color": "green", "border": "2px solid green"});
$("h3").contents().css("background-color", "yellow");
});
</script>
</head>
<body> <h1> Welcome to the shop </h1>
<div>
<h2> List of fruits </h2>
<h3>
<span>name of the fruits</span></h3>
<div>
<p> apple</p>
<p>orange</p>
</div>
<h1> Thank you </h1>
</div>
</body>
</html>
Example:
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script></script>
<script>
$(document).ready(function(){
$("p").closest("div").css({"color": "red", "border": "2px solid red"});
$("h1").find("span").css("background-color", "yellow");
});
</script></head>
<body> <h1> Welcome to the shop </h1>
<div>
<h2> List of fruits </h2>
<h3><span>name of the fruits</span></h3>
<div>
<h4>
<p> apple</p>
<p>orange</p>
</h4>
</div>
<h1> <span>Thank you </span></h1>
</div>
</body></html>
Example:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function(){
$("p#title").next("p").css("border","2px solid red");
$("p:first").nextAll().css("color", "green");
$("li.start").nextUntil("h3").css("background-color", "yellow");
});
</script>
</head>
<body>
<div>
<h1> list of fruits are </h1>
<p id="title"> apple </p>
<p> orange </p>
<p> banana </p>
</div>
<div>
<h2>list of vegetables</h2>
<ul> <li class="start"> onion </li>
<li> tomato </li>
<li> potato</li>
<li> carrot </li>
</ul>
<h3> Thank you!! visit again </h3>
</div>
</body>
</html>
Example:
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function(){
$("p").offsetParent().css("background-color", "red");
$("p").parent().css("background-color", "yellow");
});
</script>
</head>
<body>
<div style="border:1px solid black;width:70%;position:absolute;left:10px;top:50px">
<div>
<h1> list of fruits are </h1>
<div>
<p> orange </p>
<p> banana </p>
<p> apple </p>
<p> grapes </p>
</div>
</div>
</div>
</body>
</html>
Example:
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function(){
$("p").parents().css({"color": "green", "border": "2px solid red"});
});
</script>
</head>
<body>
<div>
<div>
<h1> list of fruits are </h1>
<div>
<p> orange </p>
<p> banana </p>
<p> apple </p>
<p> grapes </p>
</div>
</div>
</div>
Example:
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function(){
$("span").parentsUntil("div").css({"color": "green", "border": "2px solid red"});
});
</script>
</head>
<body>
<div> div (great-grandparent)
<ul> ul (grandparent) <br>
<li> li (direct parent)<br>
<span> span</span>
</li>
</ul>
</div>
</body>
Example:
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function(){
$("p#item1").prev("p").css("background-color", "red");
$("p#item2").prevAll("p").css("background-color", "green");
$("li.start").prevUntil("h2").css("background-color", "yellow");
});
</script>
</head>
<body>
<div>
<h1> list of fruits are </h1>
<p> apple </p>
<p> orange </p>
<p id="item1"> banana </p>
</div>
<div>
<h1> list of drinking items </h1>
<p> coffee </p>
<p> tea </p>
<p id="item2">juice </p>
</div>
<div>
<h2>list of vegetables</h2>
<ul> <li> onion </li>
<li> tomato </li>
<li> potato</li>
<li class="start"> carrot </li>
</ul>
</div></body></html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function(){
$("p.start").siblings("p").css("background-color", "yellow");
});
</script>
</head>
<body>
<div>
<h1> list of fruits are </h1>
<p> apple </p>
<p> orange </p>
<p class="start"> banana </p>
</div>
</body>
</html>
4.Looking at Some Additional jQuery Object Methods
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function(){
$("h1").add("h2").add("span").css("background-color", "yellow");
$("p:first").nextAll("p").andSelf().css("color", "green");
});
</script>
</head>
<body>
<h1> list of fruits are </h1>
<p> apple </p>
<p> orange </p>
<p> banana </p>
<span>choose any one</span>
<h2> thank you </h2>
</body>
</html>
Example:
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("li").each(function(){
$(this).css("color","red");
});
});
$("p").first().css("color","green").end().eq(1).css("background-color", "yellow");
});</script></head>
<body>
<button>Alert the value of each list item</button>
<ul>
<li>Coffee</li>
<li>Milk</li>
<li>Soda</li>
</ul>
<div>
<h1> list of fruits are </h1>
<p> apple </p>
<p> orange </p>
<p> banana </p>
</div>
</body></html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function(){
$(".menu").each (function(){
$v=$(this);
if($v.is("span")){
$v.css("color","red");
}
});
});
</script></head>
<body>
<div>
<h1 class="menu">Welcome to the website</h1>
<span class="menu">Thank you.. visit again!!</span>
</div>
</body></html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
var array = [55, 12, 49, 89, 34, 88];
var newArray = jQuery.map(array, function(val) {
return val + 5;
});
alert(newArray);
});
});
</script> </head>
<body>
<button> Click me to create new array </button>
</body> </html>
Applying JavaScript and jQuery Events for Richly Interactive Web
Pages
1. Understanding Events
2. Using the Page Load Events for Initialization
3. Adding and Removing Event Handlers to DOM Elements
4. Triggering Events Manually
5. Creating Custom Events
6. Implementing Callbacks
1.Understanding Events
● An event represents the precise moment when something happens.
● The following list describes the important things that happen when a user
interacts with the web page or browser window.
1. A physical event happens—A physical event occurs; for example, a user
clicks or moves the mouse or presses a key.
2. Events are triggered in the browser—The user interaction results in
events being triggered by the web browser—often, multiple events at the
same time.
For example, when a user types a key on the keyboard, three events are
triggered: the keypressed, keydown, and keyup events
3. The browser creates an object for the event
4.User event handlers are called
● Handlers are created in JavaScript that will interact with the event objects.
● There are three phases
○ Capturing→ The capturing phase is on the way down to the target
HTML element from the document directly through each of the parent
elements.
■ By default, behavior for event handlers for the capturing phase is
disabled.
○ Target—The target phase occurs when the event is in the HTML element
where it was initially triggered.
○ Bubbling—The bubbling phase is on the way up through each of the
parents of the target HTML element, all the way back to the document.
■ By default, the bubbling phase is enabled for events.
5.Browser handlers are called
● In addition to user event handlers, the browser has default
handlers that do different things based on the event that was
triggered.
● For example, when the user clicks a link, the browser has an event
handler that gets called and navigates to the href location
specified in the link.
Event objects
Event objects get created by the browser when it detects that an
event has occurred
Javascript and jQuery event object attributes
Important methods of event objects
Reviewing Event Types supported by javascript and jQuery
2.Using the Page Load Events for Initialization
Using the JavaScript onload Event
<html>
<body onload="myFunction()">
<script>
function myFunction() {
alert("Page is loaded");
}
</script>
</body>
</html>
Adding Initialization Code in jQuery
1.ready() jQuery method
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function(){
$("h1").css("color","red");
});
</script>
</head>
<body>
<h1> welcome to the website </h1>
</body>
</html>
2.load() jQuery method
● Using the .load() jQuery method will trigger the initialization code to
run after all page resources have loaded and are rendered to the
User.
● The load() method deprecated in jQuery version 1.8. It was
completely removed in version 3.0.
3.Adding and Removing Event Handlers to DOM Elements
An event handler is a JavaScript function that adds, removes, or alters DOM elements
Adding Event Handlers in JavaScript
● To add an event handler in JavaScript, call addEventListener() on the DOM object.
● The addEventListener() function takes three parameters:
○ event type
○ function to call, and
○ Boolean that specifies
■ true - capturing phase
■ false - bubbling phase.
Syntax:
addEventListener(“event”, Function, usecapture);
removeEventListener(“event”, function, usecapture);
Example:
window.addEventListener( "load", startTimer, false );
window.removeEventListener( "load", startTimer, false );
Onload
<html>
<head>
<script>
function start()
{
window.alert("welcome");
}
window.addEventListener("load",start,false);
</script>
</head>
<body></body></html>
Mouse events:
mousemove - The event occurs when the pointer is moving while it is over an
element
mouseover - The event occurs when the pointer is moved onto an element
mouseout - The event occurs when a user moves the mouse pointer out of an
element
Example(mousemove and mouseout)
<html>
<head>
<title> mouse events </title>
</head>
<body>
<h1 id="move">My college and My department </h1>
<script>
document.getElementById("move").addEventListener("mousemove",moveone,false);
document.getElementById("move").addEventListener("mouseout",leaveone,false);
function moveone()
{
document.getElementById("move").innerHTML="kongu Engineering college";
}
function leaveone()
{
document.getElementById("move").innerHTML="Computer Technology";
}
</script></body></html>
Applying Event Handlers in jQuery
● In the past, jQuery has had a couple of ways to add and remove event handlers,
including bind()/unbind() and delegate()/undelegate().
● bind()-Attach a handler to an event for the elements.
● delegate()-Attach a handler to one or more events for all elements that match the
selector
● unbind()-Remove a previously-attached event handler from the elements.
● undelegate()-Remove a handler from the event for all elements which match the
current selector,
● As of jQuery 1.7, these methods have all been replaced by a simple pair, on() and
on()
● Event handlers are attached to jQuery objects using the on() method.
● Syntax:
○ on(events [, selector] [, data], handler(eventObject))
○ on(events-map [, selector][, data])
● events—One or more space-separated event types and optional namespaces
denoted by dot syntax;
○ for example,"click", "mouseenter mouseleave", or
"keydown.myPlugin".
● events-map—A mapping object in which the string keys specify one or more
space-separated event types, and then the values specify handler functions
that will be called when the event is triggered;
○ for example, {'click':myhandler}
● selector—Optional
● data—Optional
● handler(eventObject)—If you are not using an eventsmap, you will need to
specify the handler function that will be executed when the event is
triggered
off()
To remove an event handler from elements using jQuery, call the off() method on
the jQuery object.
Syntax:
off(events [, selector] [, handler(eventObject]))
off(events-map [, selector])
Example(on and off)
<html><head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function(){
$("p").on("mouseenter", function(){
$(this).css("background-color", "pink");
});
$("p").on("mouseleave", function(){
alert("Bye! You now leave p!");
});
$("button").click(function(){
$("p").off("mouseenter mouseleave");
});
});
</script>
</head>
<body>
<p>mouse enter to change the color.</p>
<button> click </button>
</body>
</html>
4.Triggering Events Manually
Triggering Events in JavaScript
It involves a three-step process
● The first step is to create an event object using the
document.createEvent() method. The createEvent() method requires
that you specify the event type for the object that is being created.
● The next step is to initialize the event object with values by calling
the events’ initialization function.
● The final step is to call dispatchEvent() on the HTML object that you
want to trigger the event for.
Common Event Types Supported by createEvent()
Example
<html>
<head>
<script>
function myFunction(event) {
const ev = document.createEvent("MouseEvent");
ev.initMouseEvent("mouseover", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0,
null);
document.getElementById("myDiv").dispatchEvent(ev);
}
</script></head>
<body>
<h1>Trigger the event</h1>
<div id="myDiv"
style="padding:50px;background-color:yellow;"
onmouseover="this.innerHTML += '*';"></div>
<button onclick="myFunction(event)">Simulate Mouse Over</button>
</body></html>
note:/*initMouseEvent(type, canBubble, cancelable, view,
detail, screenX, screenY, clientX, clientY,
ctrlKey, altKey, shiftKey, metaKey,
button, relatedTarget)*/
Using jQuery to Trigger Events Manually
● jQuery also provides a way to trigger events while specifying the
values of the event object using the trigger() method.
● There are two different syntaxes for the trigger() method, as
listed
○ trigger(eventType [, extraParameters])
■ $(".checkbox").trigger("click");
○ trigger( eventObject)
■ $("input.bigText").trigger({'type':'keypress','charCode':1
3});
Example(trigger)
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("input").trigger("select");
});
});
</script>
</head>
<body>
<input type="text" value="Hello World"><br><br>
<button>Trigger the select event for the input field</button>
</body>
</html>
5.Creating Custom Events
Adding Custom Events Using JavaScript
<html><body>
<p id="p1">Hello World</p>
<script>
const e = document.createEvent("Event");
e.initEvent("myEvent", true, true);
document.getElementById("p1").addEventListener( "myEvent",myfun,false);
function myfun()
{
document.getElementById("p1").innerHTML = "Changed";
}
document.getElementById("p1").dispatchEvent(e);
</script></body></html>
Adding Custom Events Using jQuery
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
</head>
<body>
<script>
$(document).ready(function () {
$("button").click(function () {
$("p").trigger("hello", ["hello"]);
});
$("p").on("hello", function (e, message) {
alert(message);
});
});
</script>
<p id="p">Hello World</p>
<button>Click</button>
</body>
</html>
6.Implementing Callbacks
● The callback mechanism is used by calling $.Callbacks(flags) to create a callbacks
object.
● The purpose of the flags attribute is to provide the capability to specify the
behavior that should occur when different callback functions are executed.
● The possible values for flags are as follows:
once—Functions added are fired only once.
memory—As new functions are added, they are fired right away with the same values
as the last time callbacks were fired.
unique—Allows the callback functions to be added only once.
stopOnFalse—Stops firing other callback functions if one of the functions fired
returns a false.
● The callbacks object supports adding functions using the
add(functionName) method and removing functions using the
remove(functionName) method.
● To fire the callback list, call the fire() method. You can also disable
the list using the disable() method.
Example
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script> </head>
<body>
<h1>
Callbacks
</h1>
<button onclick="myfunction();">
click here
</button>
<p id="p1"></p>
<script>
function myfunction() {
var mypara = document.getElementById("p1");
var result = "";
var callbacks = jQuery.Callbacks("unique stopOnFalse");
function fun1(val) {
result = result + "function 1" + "and value is " + val + "<br>";
mypara.innerHTML = result;
};
callbacks.add(fun1);
callbacks.fire("KEC");
callbacks.add(fun1);
callbacks.fire("CT-PG");
}</script></body></html>
Using Deferred Objects
● A deferred object is an object that contains a set of functions that can be run at a
later time.
● It can register multiple callbacks into callback queues, invoke callback queues
● syntax:
jQuery.Deferred()
<html><head>
<script src="https://code.jquery.com/jquery-3.5.0.js">
</script></head>
<body>
<h1>Deferred object</h1>
<button onclick = "myfun();">click here </button>
<div id="div1"> </div>
<script> function myfun() {
function Func1(val, div){
$(div).append("Function1 Callbacks - " +
val);
}
function Func2(val, div){
$(div).append("Function2 callbacks - " +
val);
}
var def = $.Deferred();
def.done(Func1, Func2);

More Related Content

Similar to UNIT 1 (7).pptx

HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPTHSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
AAFREEN SHAIKH
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
Marlon Jamera
 
Wt unit 2 ppts client side technology
Wt unit 2 ppts client side technologyWt unit 2 ppts client side technology
Wt unit 2 ppts client side technology
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 
Wt unit 2 ppts client sied technology
Wt unit 2 ppts client sied technologyWt unit 2 ppts client sied technology
Wt unit 2 ppts client sied technology
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 
jQuery -Chapter 2 - Selectors and Events
jQuery -Chapter 2 - Selectors and Events jQuery -Chapter 2 - Selectors and Events
jQuery -Chapter 2 - Selectors and Events
WebStackAcademy
 
Unit3.pptx
Unit3.pptxUnit3.pptx
Unit3.pptx
AnamikaRai59
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
Anjan Banda
 
J query
J queryJ query
JS basics
JS basicsJS basics
JS basics
Mohd Saeed
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
Hoat Le
 
Angular JS2 Training Session #1
Angular JS2 Training Session #1Angular JS2 Training Session #1
Angular JS2 Training Session #1
Paras Mendiratta
 
jQuery
jQueryjQuery
Wt unit 5
Wt unit 5Wt unit 5
Wt unit 5
team11vgnt
 
Introducing jQuery
Introducing jQueryIntroducing jQuery
Introducing jQuery
Wildan Maulana
 
Jquery library
Jquery libraryJquery library
Oojs 1.1
Oojs 1.1Oojs 1.1
Oojs 1.1
Rodica Dada
 
BITM3730 10-3.pptx
BITM3730 10-3.pptxBITM3730 10-3.pptx
BITM3730 10-3.pptx
MattMarino13
 
Jquery
JqueryJquery
BITM3730 10-4.pptx
BITM3730 10-4.pptxBITM3730 10-4.pptx
BITM3730 10-4.pptx
MattMarino13
 
JavaScript lesson 1.pptx
JavaScript lesson 1.pptxJavaScript lesson 1.pptx
JavaScript lesson 1.pptx
MuqaddarNiazi1
 

Similar to UNIT 1 (7).pptx (20)

HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPTHSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Wt unit 2 ppts client side technology
Wt unit 2 ppts client side technologyWt unit 2 ppts client side technology
Wt unit 2 ppts client side technology
 
Wt unit 2 ppts client sied technology
Wt unit 2 ppts client sied technologyWt unit 2 ppts client sied technology
Wt unit 2 ppts client sied technology
 
jQuery -Chapter 2 - Selectors and Events
jQuery -Chapter 2 - Selectors and Events jQuery -Chapter 2 - Selectors and Events
jQuery -Chapter 2 - Selectors and Events
 
Unit3.pptx
Unit3.pptxUnit3.pptx
Unit3.pptx
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
 
J query
J queryJ query
J query
 
JS basics
JS basicsJS basics
JS basics
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
 
Angular JS2 Training Session #1
Angular JS2 Training Session #1Angular JS2 Training Session #1
Angular JS2 Training Session #1
 
jQuery
jQueryjQuery
jQuery
 
Wt unit 5
Wt unit 5Wt unit 5
Wt unit 5
 
Introducing jQuery
Introducing jQueryIntroducing jQuery
Introducing jQuery
 
Jquery library
Jquery libraryJquery library
Jquery library
 
Oojs 1.1
Oojs 1.1Oojs 1.1
Oojs 1.1
 
BITM3730 10-3.pptx
BITM3730 10-3.pptxBITM3730 10-3.pptx
BITM3730 10-3.pptx
 
Jquery
JqueryJquery
Jquery
 
BITM3730 10-4.pptx
BITM3730 10-4.pptxBITM3730 10-4.pptx
BITM3730 10-4.pptx
 
JavaScript lesson 1.pptx
JavaScript lesson 1.pptxJavaScript lesson 1.pptx
JavaScript lesson 1.pptx
 

More from DrDhivyaaCRAssistant

UNIT 1 (8).pptx
UNIT 1 (8).pptxUNIT 1 (8).pptx
UNIT 1 (8).pptx
DrDhivyaaCRAssistant
 
Unit – II (1).pptx
Unit – II (1).pptxUnit – II (1).pptx
Unit – II (1).pptx
DrDhivyaaCRAssistant
 
UNIT V (5).pptx
UNIT V (5).pptxUNIT V (5).pptx
UNIT V (5).pptx
DrDhivyaaCRAssistant
 
UNIT IV (4).pptx
UNIT IV (4).pptxUNIT IV (4).pptx
UNIT IV (4).pptx
DrDhivyaaCRAssistant
 
UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
DrDhivyaaCRAssistant
 
UNIT II (7).pptx
UNIT II (7).pptxUNIT II (7).pptx
UNIT II (7).pptx
DrDhivyaaCRAssistant
 
UNIT I (6).pptx
UNIT I (6).pptxUNIT I (6).pptx
UNIT I (6).pptx
DrDhivyaaCRAssistant
 
UNIT V (5).pptx
UNIT V (5).pptxUNIT V (5).pptx
UNIT V (5).pptx
DrDhivyaaCRAssistant
 
UNIT IV (4).pptx
UNIT IV (4).pptxUNIT IV (4).pptx
UNIT IV (4).pptx
DrDhivyaaCRAssistant
 
UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
DrDhivyaaCRAssistant
 
UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
DrDhivyaaCRAssistant
 
UNIT II (7).pptx
UNIT II (7).pptxUNIT II (7).pptx
UNIT II (7).pptx
DrDhivyaaCRAssistant
 
UNIT 1 (7).pptx
UNIT 1 (7).pptxUNIT 1 (7).pptx
UNIT 1 (7).pptx
DrDhivyaaCRAssistant
 
UNIT II (7).pptx
UNIT II (7).pptxUNIT II (7).pptx
UNIT II (7).pptx
DrDhivyaaCRAssistant
 
UNIT 1 (7).pptx
UNIT 1 (7).pptxUNIT 1 (7).pptx
UNIT 1 (7).pptx
DrDhivyaaCRAssistant
 

More from DrDhivyaaCRAssistant (15)

UNIT 1 (8).pptx
UNIT 1 (8).pptxUNIT 1 (8).pptx
UNIT 1 (8).pptx
 
Unit – II (1).pptx
Unit – II (1).pptxUnit – II (1).pptx
Unit – II (1).pptx
 
UNIT V (5).pptx
UNIT V (5).pptxUNIT V (5).pptx
UNIT V (5).pptx
 
UNIT IV (4).pptx
UNIT IV (4).pptxUNIT IV (4).pptx
UNIT IV (4).pptx
 
UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
 
UNIT II (7).pptx
UNIT II (7).pptxUNIT II (7).pptx
UNIT II (7).pptx
 
UNIT I (6).pptx
UNIT I (6).pptxUNIT I (6).pptx
UNIT I (6).pptx
 
UNIT V (5).pptx
UNIT V (5).pptxUNIT V (5).pptx
UNIT V (5).pptx
 
UNIT IV (4).pptx
UNIT IV (4).pptxUNIT IV (4).pptx
UNIT IV (4).pptx
 
UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
 
UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
 
UNIT II (7).pptx
UNIT II (7).pptxUNIT II (7).pptx
UNIT II (7).pptx
 
UNIT 1 (7).pptx
UNIT 1 (7).pptxUNIT 1 (7).pptx
UNIT 1 (7).pptx
 
UNIT II (7).pptx
UNIT II (7).pptxUNIT II (7).pptx
UNIT II (7).pptx
 
UNIT 1 (7).pptx
UNIT 1 (7).pptxUNIT 1 (7).pptx
UNIT 1 (7).pptx
 

Recently uploaded

KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsKuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
Victor Morales
 
A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...
nooriasukmaningtyas
 
ML Based Model for NIDS MSc Updated Presentation.v2.pptx
ML Based Model for NIDS MSc Updated Presentation.v2.pptxML Based Model for NIDS MSc Updated Presentation.v2.pptx
ML Based Model for NIDS MSc Updated Presentation.v2.pptx
JamalHussainArman
 
Casting-Defect-inSlab continuous casting.pdf
Casting-Defect-inSlab continuous casting.pdfCasting-Defect-inSlab continuous casting.pdf
Casting-Defect-inSlab continuous casting.pdf
zubairahmad848137
 
International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...
gerogepatton
 
Engineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdfEngineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdf
abbyasa1014
 
Recycled Concrete Aggregate in Construction Part II
Recycled Concrete Aggregate in Construction Part IIRecycled Concrete Aggregate in Construction Part II
Recycled Concrete Aggregate in Construction Part II
Aditya Rajan Patra
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
Madan Karki
 
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
ihlasbinance2003
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
SUTEJAS
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
kandramariana6
 
Modelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdfModelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdf
camseq
 
CSM Cloud Service Management Presentarion
CSM Cloud Service Management PresentarionCSM Cloud Service Management Presentarion
CSM Cloud Service Management Presentarion
rpskprasana
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
Aditya Rajan Patra
 
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
171ticu
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
IJECEIAES
 
Eric Nizeyimana's document 2006 from gicumbi to ttc nyamata handball play
Eric Nizeyimana's document 2006 from gicumbi to ttc nyamata handball playEric Nizeyimana's document 2006 from gicumbi to ttc nyamata handball play
Eric Nizeyimana's document 2006 from gicumbi to ttc nyamata handball play
enizeyimana36
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
IJECEIAES
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
IJECEIAES
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
gerogepatton
 

Recently uploaded (20)

KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsKuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
 
A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...
 
ML Based Model for NIDS MSc Updated Presentation.v2.pptx
ML Based Model for NIDS MSc Updated Presentation.v2.pptxML Based Model for NIDS MSc Updated Presentation.v2.pptx
ML Based Model for NIDS MSc Updated Presentation.v2.pptx
 
Casting-Defect-inSlab continuous casting.pdf
Casting-Defect-inSlab continuous casting.pdfCasting-Defect-inSlab continuous casting.pdf
Casting-Defect-inSlab continuous casting.pdf
 
International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...
 
Engineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdfEngineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdf
 
Recycled Concrete Aggregate in Construction Part II
Recycled Concrete Aggregate in Construction Part IIRecycled Concrete Aggregate in Construction Part II
Recycled Concrete Aggregate in Construction Part II
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
 
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
 
Modelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdfModelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdf
 
CSM Cloud Service Management Presentarion
CSM Cloud Service Management PresentarionCSM Cloud Service Management Presentarion
CSM Cloud Service Management Presentarion
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
 
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
 
Eric Nizeyimana's document 2006 from gicumbi to ttc nyamata handball play
Eric Nizeyimana's document 2006 from gicumbi to ttc nyamata handball playEric Nizeyimana's document 2006 from gicumbi to ttc nyamata handball play
Eric Nizeyimana's document 2006 from gicumbi to ttc nyamata handball play
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
 

UNIT 1 (7).pptx

  • 1. UNIT I Java Script and jQuery
  • 2. Contents Query and JavaScript Syntax – Understanding and Using JavaScript Objects - Accessing DOM Elements Using JavaScript and jQuery Objects – Navigating and Manipulating jQuery Objects and DOM Elements with jQuery – Applying JavaScript and jQuery Events for Richly Interactive Web Pages.
  • 3. Query and JavaScript Syntax 1. Adding jQuery and JavaScript to a Web Page 2. Accessing the DOM 3. Understanding JavaScript Syntax What is jQuery? ● jQuery is a lightweight, "write less, do more", JavaScript library. ● jQuery greatly simplifies JavaScript programming. ● The purpose of jQuery is to make it much easier to use JavaScript on your website. ● 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. ● jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation.
  • 4. The jQuery library contains the following features: ● HTML/DOM manipulation ● CSS manipulation ● HTML event methods ● Effects and animations ● AJAX ● Utilities Why jQuery? There are lots of other JavaScript libraries out there, but jQuery is probably the most popular, and also the most extendable. Many of the biggest companies on the Web use jQuery, such as: ● Google ● Microsoft ● IBM ● Netflix
  • 5. 1.Adding jQuery and JavaScript to a Web Page Loading the jQuery Library <script> tag is used to load the jQuery into your web page. 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 ● In the following statements, The first loads it from the jQuery CDN source and the second loads it from the web server ○ <script src="http://code.jquery.com/jquery-latest.min.js"></script> ○ <script src="includes/js/jquery-latest.min.js"></script>
  • 6. Implementing Your Own jQuery and JavaScript ● A pair of <script> statements that load jQuery and then use it. ● The document.write() function just writes text directly to the browser to be rendered: <script src="http://code.jquery.com/jquery-latest.min.js"> </script> <script> function writeIt(){ document.write("jQuery Version " + $().jquery + " loaded."); } </script>
  • 7. Accessing HTML Event Handlers ● Each supported event is an attribute of the object that is receiving the event. ● If you set the attribute value to a JavaScript function, the browser will execute your function when the event is triggered.
  • 8. <!DOCTYPE html> <html> <head> <title>jQuery Version</title> <meta charset="utf-8" /> <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script> <script> function writeIt(){ document.write("jQuery Version " + $().jquery +" loaded."); } </script> </head> <body onload="writeIt()"> </body> </html>
  • 9. 2.Accessing the DOM Using Traditional JavaScript to Access the DOM ● Traditionally, JavaScript uses the global document object to access elements in the web page. ● The simplest method of accessing an element is to directly refer to it by id with help of getElementById() function ● Another helpful JavaScript function is getElementsByTagName() which is used to access the DOM elements ● This returns a JavaScript array of DOM elements that match the tag name.
  • 11. Using jQuery Selectors to Access HTML Elements ● Accessing HTML elements is one of jQuery’s biggest strengths. ● jQuery uses selectors that are very similar to CSS selectors to access one or more elements in the DOM; ● Query selectors are used to select and manipulate HTML element(s). ● jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types, attributes, values of attributes and much more ● All selectors in jQuery start with the dollar sign and parentheses: $(). ○ Element selector ○ #id selector ○ .class selector
  • 12. Element selector ● The jQuery element selector selects elements based on the element name.(example:$("p")) ● Example: <html> <head> <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("p").css("color", "red"); }); }); </script> </head> <body> <p>This is a paragraph.</p> <button>change color</button> </body> </html>
  • 13. #id selector ● The jQuery #id selector uses the id attribute of an HTML tag to find the specific element.(example:$("#test")) ● Example: <html> <head> <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("#p1").css("background-color", "yellow"); }); }); </script> </head> <body> <p id="p1">welcome</p> <button>change color</button> </body> </html>
  • 14. Class selector ● The jQuery .class selector finds elements with a specific class.(example:$(".test")) ● Example: <html> <head> <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script> <script> $(document).ready(function(){ $(".test").css({"background-color": "yellow", "font-size": "200%"}); }); </script> </head> <body> <p class="test">Welcome</p> </body></html>
  • 15. 3.Understanding JavaScript Syntax Creating Variables ● Variables are containers for storing data and access data from your JavaScript files. ● Variables can point to simple data types, such as numbers or strings, or they can point to more complex data types, such as objects. ● var keyword is used to define a variable in JavaScript ● Example: ○ var myString = "Some Text";
  • 16. Understanding JavaScript Data Types ● String—Stores character data as a string. ○ The character data is specified by either single or double quotes. ○ var myString = 'Some Text'; ○ var anotherString = "Some Other Text"; ● Number—Stores the data as a numerical value ○ Example ■ var myInteger = 1; ■ var cost = 1.33; ● Boolean—Stores a single bit that is either true or false. ○ Booleans are often used for flags. ○ var yes = true; ○ var no = false; ● Array—An indexed array is a series of separate distinct data items all stored under a single variable name ○ var arr = ["one", "two", "three"] ○ var first = arr[0];
  • 17. ● Associative Array/Objects ○ An associative array is an array with string keys rather than numeric keys. Associative arrays are dynamic objects that the user redefines as needed. ○ var obj = {"name":"Brad", "occupation":"Hacker", "age","Unknown"}; ○ var name = obj.name; Using Operators ● Arithmetic Operators(=,+,-,/,*,+=,-=,*=,/=,%=) ● Comparison Operators(==,!=,>,>=,<,<=,===,!=,&&,!!,!) Conditional statements ● if statement ● if-else statement ● Nested if statement ● Switch case
  • 18. Looping statements ● while loops ● do while loops ● for loops ● for in loops Creating functions ● Defining Functions ○ Functions are defined using the keyword function followed by a function name that describes the use of the function, list of zero or more arguments in () parentheses, and a block of one or more code statements in {} brackets. ● Passing Variables to Functions ● Returning Values from Functions
  • 19. Example: <html> <head> <script type="text/javascript"> var a=10,b=20; function add(a,b) { c=a+b; return c; } document.write("the result is"+add(a,b)); </script> </head> <body> </body> </html>
  • 20. Understanding Variable Scope ● Each identifier in a program also has a scope. ● Global variables or script-level variables that are declared in the head element are accessible in any part of a script and are said to have global scope ● Identifiers declared inside a function have function (or local) scope and can be used only in that function. ● If a local variable in a function has the same name as a global variable, the global variable is “hidden” from the body of the function.
  • 21. <!DOCTYPE html> <html> <head> <meta charset = "utf-8"> <title>scope</title> <script> var x = 1;// global scope function start() { functionA(); functionB(); functionA(); functionB(); } function functionA() { var x = 25;//local scope document.writeln("the value of x is"+x+"<br>"); x++; document.writeln("the value of x is"+x+"<br>"); } function functionB() { document.writeln("the value of x is"+x+"<br>"); x = x*10; document.writeln("the value of x is"+x+"<br>"); } start(); </script> </head><body> </body> </html>
  • 22. Adding Error Handling ● The try statement defines a code block to run (to try). ● The catch statement defines a code block to handle any error. ● The finally statement defines a code block to run regardless of the result. ● The throw statement defines a custom error.
  • 23. Example <html> <body> <script> function sqrRoot(x) { try { if(isNaN(x)) throw "Can't Square Root Strings"; if(x>0) return "sqrt= " + Math.sqrt(x); } catch(err) { return err; } } function writeIt() { document.write(sqrRoot("four") + "<br>"); document.write(sqrRoot(4) + "<br>"); } writeIt(); </script></body></html>
  • 24. Understanding and Using JavaScript Objects 1. Using object syntax 2. Understanding Built-in Objects 3. Creating Custom-Defined Objects 1.Using object syntax Object ● An object is really a container to group multiple values and, in some instances, functions together. ● The values of an object are called properties, and functions are called methods.
  • 25. Creating a New Object Instance ● Object instances are created using the new keyword with the object constructor name. For example, to create a Number object, you use the following line of code: ○ var x = new Number("5"); Accessing Object Properties ● All JavaScript objects have values that are accessible via a standard dot-naming syntax. ● For example, consider an object with the variable name user that contains a property firstName. ○ user.FirstName Accessing Object Methods ● An object method is a function that is attached to the object as a name. The function can be called by using the dot syntax to reference the method name ○ user.getFullName()
  • 26. 2.Understanding Built-in Objects Number ● The Number object provides functionality that is useful when dealing with numbers. ● var x = new Number("5.55555555");
  • 27. Example: <html> <body> <h2>JavaScript Number Methods</h2> <script> var x = 9.656; document.write(x.toExponential()+"<br>"); document.write(x.toFixed(2)+"<br>"); document.write(x.toPrecision(6)+"<br>"); document.write(x.valueOf()); </script> </body></html>
  • 28. String ● JavaScript automatically creates a String object anytime you define a variable that has a string data type ● var myStr = "Welcome";
  • 29. <!DOCTYPE html> <html> <body> <h1>JavaScript Strings</h1> <script> var text = "HELLO WORLD"; var text1 = "sea"; var text2 = "food"; let text3 = "Hello planet earth, you are a great planet"; var letter = text.charAt(0); document.write(letter+"<br>"); var code = text.charCodeAt(0); document.write(code+"<br>"); var result = text1.concat(text2); document.write(result+"<br>"); var mytext = String.fromCharCode(65); document.write(mytext+"<br>"); let r = text3.indexOf("planet"); document.write(r+"<br>"); let r1 = text3.lastIndexOf("planet"); document.write(r1); </script> </body> </html>
  • 30.
  • 31.
  • 32. <!DOCTYPE html> <html> <body> <h1>JavaScript Strings</h1> <script> let text = "The rain in SPAIN stays mainly in the plain"; let result = text.match(/rain/); document.write(result+"<br>"); document.write(text.replace("SPAIN", "London")+"<br>"); document.write(text.search("rain")+"<br>"); document.write(text.slice(0,5)+"<br>"); document.write(text.split(" ",3)+"<br>"); document.write(text.substr(4, 3)+"<br>"); document.write(text.substring(1, 4)); </script> </body> </html>
  • 33. Array ● The Array object provides a means of storing and handling a set of other objects. Arrays can store numbers, strings, or other JavaScript var arr = ["one", "two", "three"];
  • 34. Example: <html> <body> <h1>JavaScript Arrays</h1> <script> const arr1 = ["apple", "banana"]; const arr2 = ["orange", "grapes", "Lemon","orange"]; const children = arr1.concat(arr2); document.write(children+"<br>"); document.write(arr2.indexOf("Lemon")+"<br>"); document.write(arr2.join(" & ")+"<br>"); document.write(arr2.lastIndexOf("orange")+"<br>"); document.write(arr2.pop()+"<br>"); document.write(arr2+"<br>"); arr2.push("Mango"); document.write(arr2+"<br>"); document.write(arr2.reverse()); </script> </body>
  • 35.
  • 36. <html> <body> <h1>JavaScript Arrays</h1> <script> const arr2 = ["orange", "grapes", "Lemon","orange"]; document.write(arr2.shift()+"<br>"); document.write(arr2+"<br>"); document.write(arr2.slice(0, 2)+"<br>"); arr2.splice(2, 1, "mango", "Kiwi") document.write(arr2+"<br>"); arr2.splice(2, 2); document.write(arr2+"<br>"); arr2.unshift("apple", "Pineapple"); document.write(arr2+"<br>"); document.write(arr2.sort()); </script> </body> </html>
  • 37. Date The Date object provides access to the current time on the browser’s system <!DOCTYPE html> <html> <body> <h1>JavaScript Dates</h1> <script> const d = new Date(); document.write(d) </script> </body> </html>
  • 38.
  • 39.
  • 40.
  • 41. <!DOCTYPE html> <html> <head> <meta charset = "utf-8"> <title>Date Object Methods</title> <script type="text/javascript"> var current = new Date(); document.write("<h1>String representations and valueOf</h1>"); document.write("<br>toString:"+current.toString()); document.write("<br>toLocaleString:"+current.toLocaleString()); document.write("<br>toUTCString:"+current.toUTCString()); document.write("<br>valueOf:"+current.valueOf());
  • 42. document.write("<h1>Get methods for local time zone</h1>"); document.write("<br>getDate:"+current.getDate()); document.write("<br>getDay:"+current.getDay()); document.write("<br>getMonth:"+current.getMonth()); document.write("<br>getFullYear:"+current.getFullYear()); document.write("<br>getTime:"+current.getTime()); document.write("<br>getHours:"+current.getHours()); document.write("<br>getMinutes:"+current.getMinutes()); document.write("<br>getSeconds:"+current.getSeconds()); document.write("<br>getMilliseconds:"+current.getMilliseconds()); document.write("<br>getTimezoneOffset:"+current.getTimezoneOffset());
  • 43. document.write("<h1>Specifying arguments for a new Date</h1>"); var anotherDate = new Date( 2021, 3, 18, 1, 5, 0, 0 ); document.write(anotherDate); </script> <body> </body> </html>
  • 44.
  • 45. Math The Math object is really an interface to a mathematical library that provides a ton of time-saving functionality <!DOCTYPE html> <html> <head> <title> math object</title> <meta charset="UTF-8"> <script type="text/javascript"> var result = Math.sqrt( 900 ); document.write(result); </script> <body> </body></html>
  • 47.
  • 48. RegExp ● When dynamically processing user input or even data coming back from the web server, an important tool is regular expressions. ● Regular expressions allow you to quickly match patterns in text and then act on those patterns. ● var re =/pattern/modifiers; ● Available modifiers in JavaScript i—Perform matching that is not case sensitive. g—Perform a global match on all instances rather than just the first. m—Perform multiline match
  • 49. <!DOCTYPE html> <html> <body> <h2>JavaScript Regular Expressions</h2> <script> var myStr = "Teach Yourself jQuery & JavaScript in 24 Lessons"; var re = /yourself/i; var newStr = myStr.replace(re, "Your Friends"); document.write(newStr); </script> </body> </html>
  • 50. 3.Creating Custom-Defined Objects ● Objects are variables too. But objects can contain many values. ● Object values are written as name : value pairs (name and value separated by a colon). ● var user = new Object(); ○ user.first="Brad"; ○ user.last="Dayley"; ● var user = {'first':'Brad','last':'Dayley'}; ● document.write(user.first + " " + user.last);
  • 51. Adding Methods to JavaScript Objects <html> <body> <h2>JavaScript Objects</h2> <script> var user = new Object(); user.first="abi"; user.last="karthi"; user.getFullName = makeFullName; var user2 = { 'first':'john', 'last':'David', 'getFullName':makeFullName }; function makeFullName() { return this.first + " " + this.last; } var user3 = { first: "John", last: "Peter", getFullName : function() { return this.first + " " + this.last; } };
  • 53. Using a Prototyping Object Pattern→ The prototyping pattern is implemented by defining the functions inside the prototype attribute of the object instead of the object itself. <html> <body> <h1> Using a Prototyping Object Pattern </h1> <script> function User(first, last){ this.first = first; this.last = last; } User.prototype = { getFullName: function(){ return this.first + " " + this.last; } }; var user1 = new User("John", "Peter"); document.write(user1.getFullName()); </script> </body> </html>
  • 54. Accessing DOM Elements Using JavaScript and jQuery Objects 1. Understanding DOM Objects Versus jQuery Objects 2. Accessing DOM Objects from JavaScript 3. Using jQuery Selectors
  • 55. 1.Understanding DOM Objects Versus jQuery Objects Javascript DOM objects ● In a web page, DOM (Document Object Model) objects refer to the objects that represent the elements in the page's HTML source code. ● These objects can be manipulated using JavaScript, and can be accessed and modified using the DOM API (Application Programming Interface). ● The DOM API provides a number of functions and properties that allow you to access and modify DOM objects. ● For example, you can use the getElementById function to get a reference to an element with a specific id, or you can use the innerHTML property to get or set the HTML content of an element.
  • 56. Drawbacks ● Complexity: The DOM API can be complex to work with, as it requires you to navigate the hierarchical structure of the DOM and access elements using a variety of functions and properties. ● Browser compatibility: The DOM API can vary between different browsers, which can make it more challenging to write code that works consistently across different browsers. ● Performance: Modifying the DOM can be computationally intensive, as it requires the browser to update the layout and rendering of the page. These challenges can be mitigated to some extent by using tools such as the jQuery library, which provides a more consistent and convenient interface for working with DOM objects.
  • 57. list of some of the important attributes and methods of DOM objects
  • 58. Example:(click()) <!DOCTYPE html> <html> <body> <h2>The click() Method</h2> <form> <input type="checkbox" id="myCheck" onmouseover="myFunction()">click me </form> <script> function myFunction() { document.getElementById("myCheck").click(); } </script> </body> </html>
  • 59. Example:(parent and child node) <html> <body> <h2>The parentNode and child node Property</h2> <ul id="u1"> <li id="myLI">Coffee</li> <li>Tea</li> </ul> <p id="demo"></p> <p id="demo1"></p> <p id="demo2"></p>
  • 60. <script> let name = document.getElementById("myLI").parentNode.nodeName; document.getElementById("demo").innerHTML = "parent node is "+name; const nodeList = document.getElementById("u1").children; document.getElementById("demo1").innerHTML =nodeList.length; const nodeList1 = document.getElementById("u1").childNodes; document.getElementById("demo2").innerHTML =nodeList1.length; </script> </body> </html>
  • 61.
  • 62. Example:(outerhtml) <html> <body> <h2>The outerHTML Property</h2> <p id="myP">I am a paragraph! Click "Change" to replace me with a header.</p> <button onclick="myFunction()">Change</button> <script> function myFunction() { const element = document.getElementById("myP"); element.outerHTML = "<h2>This is a h2 element.</h2>"; } </script> </body> </html>
  • 63.
  • 64. Example:(getattribute) <html> <head> <style> .democlass { color: red; } </style> <script> function myFunction() { var x = document.getElementById("a").getAttribute("class"); document.getElementById("demo").innerHTML = x; } </script> </head> <body> <h1 id="a" class="democlass">Hello World</h1> <input type="submit" value="click to get the attribute" onclick="myFunction()"> <p id="demo"></p> </body> </html>
  • 65. Example:(setattribute) <html> <head> <style> .democlass { color: red; } </style> <script> function myFunction() { var x = document.getElementById("a").setAttribute("class", "democlass"); } </script> </head> <body> <h1 id="a">Hello World</h1> <input type="submit" value="click to set attribute" onclick="myFunction()"> </body> </html>
  • 66. Example:(appendchild) <html> <body> <p id="p2">This is another paragraph.</p> <script> var para = document.createElement("p"); var node = document.createTextNode("This is new."); para.appendChild(node); var element = document.getElementById("p2"); element.appendChild(para); </script> </body> </html>
  • 67. jQuery Objects ● jQuery objects are basically wrapper objects around a set of DOM elements. ● jQuery objects are objects created by the jQuery library, which is a JavaScript library for simplifying HTML document traversal, event handling, and animating. ● jQuery objects are collections of DOM (Document Object Model) elements that can be manipulated using the functions and methods provided by the jQuery library. ● Query objects are designed to be more convenient to work with than DOM objects, as they provide a simpler and more consistent interface for manipulating elements in the page.
  • 68. Advantages ● Simplicity: jQuery objects provide a simple and consistent interface for interacting with DOM elements, which can make it easier to write and maintain code that manipulates these elements. ● Browser compatibility: jQuery objects abstract away many of the differences between different browsers, which can make it easier to write code that works consistently across different browsers. ● Convenience: jQuery objects provide a wide range of functions and methods for manipulating DOM elements, which can make it easier to perform common tasks such as selecting elements, modifying their attributes or styles, or handling events. ● Performance: jQuery is designed to be efficient and fast, and can often perform tasks such as DOM manipulation more quickly than equivalent code using the DOM API.
  • 69. List of some of the important methods of jQuery objects
  • 71. Example:(val() and attr()) <html> <head> <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("img").attr("width", "500"); $("input:text").val("KEC"); }); }); </script> </head> <body> <img src="img_pulpitrock.jpg" alt="Pulpit Rock"><br> <p>Name: <input type="text" name="user"></p> <button>click</button> </body> </html>
  • 72.
  • 73.
  • 74. Example:(addclass(), css()) <html><head> <style> .intro { font-size: 150%; color: red; } </style> <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("#p1").css("background-color", "yellow"); $("p").addClass("intro"); }); }); </script></head> <body> <p id="p1">welcome</p> <button>change color</button> </body> </html>
  • 75.
  • 77.
  • 78. 2.Accessing DOM Objects from JavaScript Finding DOM Objects by ID ● The simplest is to find an HTML element using the value of the id attribute using the getElementById(id) function. ● getElementById(id) searches the DOM for an object with a atching id attribute.
  • 79. Example: <html> <body> <h2>The getElementById() Method</h2> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = "Hello World"; </script> </body> </html>
  • 80. Finding DOM Objects by Class Name The getElementsByClassName() method returns a collection of child elements with a given class name. <html> <body> <h2>The getElementsByClassName() Method</h2> <div class="example">Element1</div> <div class="example">Element2</div> <script> collection = document.getElementsByClassName("example"); collection[0].innerHTML = "Hello World!"; </script> </body> </html>
  • 81. Finding DOM Objects by Tag Name ● Another way to search for HTML elements is by their HTML tag, using the getElementsByTagName(tag). ● This function returns a list of DOM objects with matching HTML tags <html> <body> <h2>The getElementsByTagName() Method</h2> <p>This is a paragraph.</p> <script> document.getElementsByTagName("p")[0].innerHTML = "Hello World!"; </script> </body> </html>
  • 82. 3.Using jQuery Selectors ● Applying Basic Selectors ● Applying Attribute Selectors ● Applying Content Selectors ● Applying Hierarchy Selectors ● Applying Form Selectors ● Applying Visibility Selectors ● Applying Filtered Selectors
  • 83. Applying Basic Selectors ● The most commonly used selectors are the basic ones. ● The basic selectors focus on the id attribute, class attribute, and tag name of HTML elements
  • 84. Class selector ● The jQuery .class selector finds elements with a specific class.(example:$(".test")) ● Example: <html> <head> <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script> <script> $(document).ready(function(){ $(".test").css({"background-color": "yellow", "font-size": "200%"}); }); </script> </head> <body> <p class="test">Welcome</p> </body></html>
  • 85. #id selector ● The jQuery #id selector uses the id attribute of an HTML tag to find the specific element.(example:$("#test")) ● Example: <html> <head> <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("#p1").css("background-color", "yellow"); }); }); </script> </head> <body> <p id="p1">welcome</p> <button>change color</button> </body> </html>
  • 86.
  • 87. Element selector ● The jQuery element selector selects elements based on the element name.(example:$("p")) ● Example: <html> <head> <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("p").css("color", "red"); }); }); </script> </head> <body> <p>This is a paragraph.</p> <button>change color</button> </body> </html>
  • 88. Applying Attribute Selectors ● Another way to use jQuery selectors is to select HTML elements by their attribute values ● Attribute values are denoted in the selector syntax by being enclosed in [] brackets
  • 89.
  • 90.
  • 91. Example: <!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script> <script> $(document).ready(function(){ $("[id=choose]").css("background-color", "yellow"); $("h1[class*=Content]").css("background-color", "green"); $("p[id][class$=menu]").css("background-color", "red"); }); </script> </head>
  • 92. <body> <h1 class="leftContent">Welcome to</h1> <h1 class="rightContent">Fruit shop</h1> Who is your favourite fruit: <ul id="choose"> <li>Apple</li> <li>Orange</li> <li>banana</li> </ul> <p id="m" class="menu"> Thank you </p> <p id="m1" class="menu1"> visit again </p> </body> </html>
  • 93. Applying Content Selectors ● Another set of useful jQuery selectors are the content filter selectors. ● These selectors are used to select HTML elements based on the content inside the HTML element
  • 94.
  • 95. Example: <!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script> <script> $(document).ready(function(){ $("p:contains(are)").css("background-color", "yellow"); $("div:has(span)").css("background-color", "red"); $("h1:parent").css("background-color", "blue"); }); </script> </head>
  • 96. <body> <h1>Welcome to the shop</h1> <p>The list of fruits are</p> <ul> <li>Apple</li> <li>Banana</li> </ul> <div>choose your <span>favorite </span></div> </body> </html>
  • 97. Applying Hierarchy Selectors ● An important set of jQuery selectors are the hierarchy selectors. ● These selectors are used to select HTML elements based on the DOM hierarchy.
  • 98.
  • 99.
  • 100. Example: <html> <head> <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script> <script> $(document).ready(function(){ $("div span").css("background-color", "yellow"); $("div.menu > span").css("background-color", "red"); $("label+input.item").css("background-color", "blue"); $("#menu ~ div").css("background-color", "green"); }); </script> </head>
  • 101. <body> <div><h1>Welocme to <span>KEC </span>Engg College</p></div> <div class="menu"> PG Department:<span> MSC(SS)</span> </div> <form> <label>search:</label> <input type="text" class="item"> </form> <div> Other departments are </div> <ul id="menu"> <li> CSE </li> <li>IT </li></ul> <div> Thank you!!! </div> <div> visit again </div> </ul></body></html>
  • 102. Applying Form Selectors ● An extremely useful set of selectors when working with dynamic HTML forms are the form jQuery selectors. ● These selectors are used to select elements in the form based on the state of the form element
  • 103.
  • 105. <body> <form> Choose your favorite color <input type="checkbox" checked="checked">Red <input type="checkbox">Green<br> select fruits: <select> <option>Apple</option> <option selected="selected">Orange</option> <option>Mango</option> <option>Banana</option> </select> Search:<input type="text" /><br><br> Give feedback:<br> <textarea disabled="disabled"> </textarea> </form> </body></html>
  • 106. Applying Visibility Selectors ● The visibility selectors are used to to control the flow and interactions of the web page components and it selects the HTML elements that are hidden or visible
  • 108. <body> <h1>This is a heading</h1> <p>This is a pargraph.</p> <p>This is another paragraph.</p> <h2 style="visibility:hidden;">This is a hidden paragraph.</h2> <p style="display:none;">This is a hidden paragraph that is slowly shown.</p> </body> </html>
  • 109. Applying Filtered Selectors ● Filtered selectors append a filter on the end of the selector statement that limits the results returned by the selector
  • 110.
  • 111.
  • 112. Example: <html> <head> <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script> <script> $(document).ready(function(){ $("li:odd").css("background-color", "orange"); $("li:even").css("background-color", "pink"); $("li:gt(1)").css("color", "white"); $("li:lt(2)").css("color", "red"); $("div:eq(1)").css("background-color", "yellow"); $("div:first").css("background-color", "green"); $(":header").css("color", "red"); });</script></head>
  • 113. <body> <h1> Welcome to the shop </h1> <div> select the fruits </div> <ul> <li>Apple </li> <li>Orange </li> <li>banana </li> <li>grape </li> </ul> <div> Thank you </div> </body> </html>
  • 114. Navigating and Manipulating jQuery Objects and DOM Elements with jQuery 1. Chaining jQuery Object Operations 2. Filtering the jQuery Object Results 3. Traversing the DOM Using jQuery Objects 4. Looking at Some Additional jQuery Object Methods
  • 115. 1.Chaining jQuery Object Operations Chaining allows us to run multiple jQuery methods (on the same element) within a single statement. Advantages: While using method chaining in jQuery, it ensures that there is no need to use the same selector more than once
  • 117. 2.Filtering the jQuery Object Results ● jQuery objects provide a good set of methods which are used to alter the DOM objects represented in the query.
  • 118.
  • 119.
  • 120. Example: <head> <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script> <script> $(document).ready(function(){ $("p").filter(".intro").css("background-color", "yellow"); $("p").eq(2).css("background-color", "red"); $("li").first().css("color", "red"); $("li").last().css("color", "green"); $("h1").has("span").css("color", "blue"); $(".menu").not("span").css("color", "orange"); $("p").slice(1,3).css("font-size", "20px"); });</script></head>
  • 121. <body> <h1>Welcome to <span class="menu">My College</span></h1> <h1 class="menu">Departments</h1> <p>BSC</p> <p class="intro">MSC</p> <p>CSE</p> <p>IT</p> <h1>Programming languages to learn</h1> <ul> <li>C</li> <li>C++</li> <li>JAVA</li> </ul></body></html>
  • 122. 3.Traversing the DOM Using jQuery Objects ● Another important set of methods attached to the jQuery object are the DOM traversing methods. ● DOM traversal is used to select elements based on their relationship to other elements. ● The DOM is referred to as the DOM tree because it is organized in a tree structure, with the document as the root and nodes that can have both parents, siblings, and children.
  • 123.
  • 124.
  • 126. <body> <h1> Welcome to the shop </h1> <div> <h2> List of fruits </h2> <h3> <span>name of the fruits</span></h3> <div> <p> apple</p> <p>orange</p> </div> <h1> Thank you </h1> </div> </body> </html>
  • 128. <body> <h1> Welcome to the shop </h1> <div> <h2> List of fruits </h2> <h3><span>name of the fruits</span></h3> <div> <h4> <p> apple</p> <p>orange</p> </h4> </div> <h1> <span>Thank you </span></h1> </div> </body></html>
  • 129.
  • 130. Example: <!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script> <script> $(document).ready(function(){ $("p#title").next("p").css("border","2px solid red"); $("p:first").nextAll().css("color", "green"); $("li.start").nextUntil("h3").css("background-color", "yellow"); }); </script> </head>
  • 131. <body> <div> <h1> list of fruits are </h1> <p id="title"> apple </p> <p> orange </p> <p> banana </p> </div> <div> <h2>list of vegetables</h2> <ul> <li class="start"> onion </li> <li> tomato </li> <li> potato</li> <li> carrot </li> </ul> <h3> Thank you!! visit again </h3> </div> </body> </html>
  • 132.
  • 134. <body> <div style="border:1px solid black;width:70%;position:absolute;left:10px;top:50px"> <div> <h1> list of fruits are </h1> <div> <p> orange </p> <p> banana </p> <p> apple </p> <p> grapes </p> </div> </div> </div> </body> </html>
  • 135.
  • 137. <body> <div> <div> <h1> list of fruits are </h1> <div> <p> orange </p> <p> banana </p> <p> apple </p> <p> grapes </p> </div> </div> </div>
  • 139. <body> <div> div (great-grandparent) <ul> ul (grandparent) <br> <li> li (direct parent)<br> <span> span</span> </li> </ul> </div> </body>
  • 140.
  • 141.
  • 143. <body> <div> <h1> list of fruits are </h1> <p> apple </p> <p> orange </p> <p id="item1"> banana </p> </div> <div> <h1> list of drinking items </h1> <p> coffee </p> <p> tea </p> <p id="item2">juice </p> </div> <div> <h2>list of vegetables</h2> <ul> <li> onion </li> <li> tomato </li> <li> potato</li> <li class="start"> carrot </li> </ul> </div></body></html>
  • 145. 4.Looking at Some Additional jQuery Object Methods
  • 146. <html> <head> <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script> <script> $(document).ready(function(){ $("h1").add("h2").add("span").css("background-color", "yellow"); $("p:first").nextAll("p").andSelf().css("color", "green"); }); </script> </head> <body> <h1> list of fruits are </h1> <p> apple </p> <p> orange </p> <p> banana </p> <span>choose any one</span> <h2> thank you </h2> </body> </html>
  • 147.
  • 149. <body> <button>Alert the value of each list item</button> <ul> <li>Coffee</li> <li>Milk</li> <li>Soda</li> </ul> <div> <h1> list of fruits are </h1> <p> apple </p> <p> orange </p> <p> banana </p> </div> </body></html>
  • 150.
  • 152. <html> <head> <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ var array = [55, 12, 49, 89, 34, 88]; var newArray = jQuery.map(array, function(val) { return val + 5; }); alert(newArray); }); }); </script> </head> <body> <button> Click me to create new array </button> </body> </html>
  • 153. Applying JavaScript and jQuery Events for Richly Interactive Web Pages 1. Understanding Events 2. Using the Page Load Events for Initialization 3. Adding and Removing Event Handlers to DOM Elements 4. Triggering Events Manually 5. Creating Custom Events 6. Implementing Callbacks
  • 154. 1.Understanding Events ● An event represents the precise moment when something happens. ● The following list describes the important things that happen when a user interacts with the web page or browser window. 1. A physical event happens—A physical event occurs; for example, a user clicks or moves the mouse or presses a key. 2. Events are triggered in the browser—The user interaction results in events being triggered by the web browser—often, multiple events at the same time. For example, when a user types a key on the keyboard, three events are triggered: the keypressed, keydown, and keyup events 3. The browser creates an object for the event
  • 155. 4.User event handlers are called ● Handlers are created in JavaScript that will interact with the event objects. ● There are three phases ○ Capturing→ The capturing phase is on the way down to the target HTML element from the document directly through each of the parent elements. ■ By default, behavior for event handlers for the capturing phase is disabled. ○ Target—The target phase occurs when the event is in the HTML element where it was initially triggered. ○ Bubbling—The bubbling phase is on the way up through each of the parents of the target HTML element, all the way back to the document. ■ By default, the bubbling phase is enabled for events.
  • 156.
  • 157. 5.Browser handlers are called ● In addition to user event handlers, the browser has default handlers that do different things based on the event that was triggered. ● For example, when the user clicks a link, the browser has an event handler that gets called and navigates to the href location specified in the link.
  • 158. Event objects Event objects get created by the browser when it detects that an event has occurred Javascript and jQuery event object attributes
  • 159.
  • 160.
  • 161. Important methods of event objects
  • 162. Reviewing Event Types supported by javascript and jQuery
  • 163.
  • 164.
  • 165.
  • 166. 2.Using the Page Load Events for Initialization Using the JavaScript onload Event <html> <body onload="myFunction()"> <script> function myFunction() { alert("Page is loaded"); } </script> </body> </html>
  • 167. Adding Initialization Code in jQuery 1.ready() jQuery method <html> <head> <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script> <script> $(document).ready(function(){ $("h1").css("color","red"); }); </script> </head> <body> <h1> welcome to the website </h1> </body> </html>
  • 168. 2.load() jQuery method ● Using the .load() jQuery method will trigger the initialization code to run after all page resources have loaded and are rendered to the User. ● The load() method deprecated in jQuery version 1.8. It was completely removed in version 3.0.
  • 169. 3.Adding and Removing Event Handlers to DOM Elements An event handler is a JavaScript function that adds, removes, or alters DOM elements Adding Event Handlers in JavaScript ● To add an event handler in JavaScript, call addEventListener() on the DOM object. ● The addEventListener() function takes three parameters: ○ event type ○ function to call, and ○ Boolean that specifies ■ true - capturing phase ■ false - bubbling phase. Syntax: addEventListener(“event”, Function, usecapture); removeEventListener(“event”, function, usecapture); Example: window.addEventListener( "load", startTimer, false ); window.removeEventListener( "load", startTimer, false );
  • 171. Mouse events: mousemove - The event occurs when the pointer is moving while it is over an element mouseover - The event occurs when the pointer is moved onto an element mouseout - The event occurs when a user moves the mouse pointer out of an element
  • 172. Example(mousemove and mouseout) <html> <head> <title> mouse events </title> </head> <body> <h1 id="move">My college and My department </h1> <script> document.getElementById("move").addEventListener("mousemove",moveone,false); document.getElementById("move").addEventListener("mouseout",leaveone,false); function moveone() { document.getElementById("move").innerHTML="kongu Engineering college"; } function leaveone() { document.getElementById("move").innerHTML="Computer Technology"; } </script></body></html>
  • 173. Applying Event Handlers in jQuery ● In the past, jQuery has had a couple of ways to add and remove event handlers, including bind()/unbind() and delegate()/undelegate(). ● bind()-Attach a handler to an event for the elements. ● delegate()-Attach a handler to one or more events for all elements that match the selector ● unbind()-Remove a previously-attached event handler from the elements. ● undelegate()-Remove a handler from the event for all elements which match the current selector, ● As of jQuery 1.7, these methods have all been replaced by a simple pair, on() and
  • 174. on() ● Event handlers are attached to jQuery objects using the on() method. ● Syntax: ○ on(events [, selector] [, data], handler(eventObject)) ○ on(events-map [, selector][, data]) ● events—One or more space-separated event types and optional namespaces denoted by dot syntax; ○ for example,"click", "mouseenter mouseleave", or "keydown.myPlugin". ● events-map—A mapping object in which the string keys specify one or more space-separated event types, and then the values specify handler functions that will be called when the event is triggered; ○ for example, {'click':myhandler}
  • 175. ● selector—Optional ● data—Optional ● handler(eventObject)—If you are not using an eventsmap, you will need to specify the handler function that will be executed when the event is triggered off() To remove an event handler from elements using jQuery, call the off() method on the jQuery object. Syntax: off(events [, selector] [, handler(eventObject])) off(events-map [, selector])
  • 176. Example(on and off) <html><head> <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script> <script> $(document).ready(function(){ $("p").on("mouseenter", function(){ $(this).css("background-color", "pink"); }); $("p").on("mouseleave", function(){ alert("Bye! You now leave p!"); }); $("button").click(function(){ $("p").off("mouseenter mouseleave"); }); }); </script> </head> <body> <p>mouse enter to change the color.</p> <button> click </button> </body> </html>
  • 177.
  • 178. 4.Triggering Events Manually Triggering Events in JavaScript It involves a three-step process ● The first step is to create an event object using the document.createEvent() method. The createEvent() method requires that you specify the event type for the object that is being created. ● The next step is to initialize the event object with values by calling the events’ initialization function. ● The final step is to call dispatchEvent() on the HTML object that you want to trigger the event for.
  • 179. Common Event Types Supported by createEvent()
  • 180. Example <html> <head> <script> function myFunction(event) { const ev = document.createEvent("MouseEvent"); ev.initMouseEvent("mouseover", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); document.getElementById("myDiv").dispatchEvent(ev); } </script></head> <body> <h1>Trigger the event</h1> <div id="myDiv" style="padding:50px;background-color:yellow;" onmouseover="this.innerHTML += '*';"></div> <button onclick="myFunction(event)">Simulate Mouse Over</button> </body></html> note:/*initMouseEvent(type, canBubble, cancelable, view, detail, screenX, screenY, clientX, clientY, ctrlKey, altKey, shiftKey, metaKey, button, relatedTarget)*/
  • 181. Using jQuery to Trigger Events Manually ● jQuery also provides a way to trigger events while specifying the values of the event object using the trigger() method. ● There are two different syntaxes for the trigger() method, as listed ○ trigger(eventType [, extraParameters]) ■ $(".checkbox").trigger("click"); ○ trigger( eventObject) ■ $("input.bigText").trigger({'type':'keypress','charCode':1 3});
  • 183. 5.Creating Custom Events Adding Custom Events Using JavaScript <html><body> <p id="p1">Hello World</p> <script> const e = document.createEvent("Event"); e.initEvent("myEvent", true, true); document.getElementById("p1").addEventListener( "myEvent",myfun,false); function myfun() { document.getElementById("p1").innerHTML = "Changed"; } document.getElementById("p1").dispatchEvent(e); </script></body></html>
  • 184. Adding Custom Events Using jQuery <html> <head> <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script> </head> <body> <script> $(document).ready(function () { $("button").click(function () { $("p").trigger("hello", ["hello"]); }); $("p").on("hello", function (e, message) { alert(message); }); }); </script> <p id="p">Hello World</p> <button>Click</button> </body> </html>
  • 185. 6.Implementing Callbacks ● The callback mechanism is used by calling $.Callbacks(flags) to create a callbacks object. ● The purpose of the flags attribute is to provide the capability to specify the behavior that should occur when different callback functions are executed. ● The possible values for flags are as follows: once—Functions added are fired only once. memory—As new functions are added, they are fired right away with the same values as the last time callbacks were fired. unique—Allows the callback functions to be added only once. stopOnFalse—Stops firing other callback functions if one of the functions fired returns a false.
  • 186. ● The callbacks object supports adding functions using the add(functionName) method and removing functions using the remove(functionName) method. ● To fire the callback list, call the fire() method. You can also disable the list using the disable() method.
  • 188. <script> function myfunction() { var mypara = document.getElementById("p1"); var result = ""; var callbacks = jQuery.Callbacks("unique stopOnFalse"); function fun1(val) { result = result + "function 1" + "and value is " + val + "<br>"; mypara.innerHTML = result; }; callbacks.add(fun1); callbacks.fire("KEC"); callbacks.add(fun1); callbacks.fire("CT-PG"); }</script></body></html>
  • 189. Using Deferred Objects ● A deferred object is an object that contains a set of functions that can be run at a later time. ● It can register multiple callbacks into callback queues, invoke callback queues ● syntax: jQuery.Deferred()
  • 190. <html><head> <script src="https://code.jquery.com/jquery-3.5.0.js"> </script></head> <body> <h1>Deferred object</h1> <button onclick = "myfun();">click here </button> <div id="div1"> </div> <script> function myfun() { function Func1(val, div){ $(div).append("Function1 Callbacks - " + val); } function Func2(val, div){ $(div).append("Function2 callbacks - " + val); } var def = $.Deferred(); def.done(Func1, Func2);