SlideShare a Scribd company logo
Unit II- Client Side
Technologies:
JavaScript and DOM
Outlin
e
, appending elements, removing elements, handling
events.
JavaScript-
Outline
• using JS in an HTML (Embedded, External),
• Data types,
• Control Structures,
• Arrays,
• Functions
• Objects
• Scopes
Overview of JavaScript,
• JavaScript is one of the 3 languages all web developers must
learn:
• 1. HTML to define the content of web pages
• 2. CSS to specify the layout of web pages
• 3. JavaScript to program the behavior of web pages
• JavaScript is a very powerful client-side scripting language.
• Javascript is a dynamic computer programming language.
•
JavaScript
• JavaScript is a front-end scripting language developed by
Netscape for dynamic content
• Lightweight, but with limited capabilities
• Can be used as object-oriented language
• Client-side technology
• Embedded in your HTML page
• Interpreted by the Web browser
• Simple and flexible
• Powerful to manipulate the DOM
6
JavaScript Advantages
• JavaScript allows interactivity such as:
• Implementing form validation
• React to user actions, e.g. handle keys
• Changing an image on moving mouse over it
• Sections of a page appearing and disappearing
• Content loading and changing dynamically
• Performing complex calculations
• Custom HTML controls, e.g. scrollable table
• Implementing AJAX functionality
7
What Can JavaScript Do?
• Can handle events
• Can read and write HTML elements
• Can validate form data
• Can access / modify browser cookies
• Can detect the user’s browser and OS
• Can be used as object-oriented language
• Can handle exceptions
• Can perform asynchronous server calls (AJAX)
8
The
JavaScript
Synta
x
JavaScript Syntax
• JavaScript can be implemented using <script>... </script> HTML tags
in a web page.
• Place the <script> tags, within the <head> tags.
• Syntax:
• <script language="javascript" type="text/javascript">
• JavaScript code
• </script>
JavaScript
Syntax
• Example:
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
</body>
</html>
• The comment ends with a "//-->". Here "//" signifies a comment
in JavaScript
• Output
Hello World!
JavaScript
Syntax
• The JavaScript syntax is similar to C# and Java
• Operators (+, *, =, !=, &&, ++, …)
• Variables (typeless)
• Conditional statements (if, else)
• Loops (for, while)
• Arrays (my_array[]) and associative arrays (my_array['abc'])
• Functions (can return value)
• Function variables (like the C# delegates)
12
Enabling JavaScript
in Browsers
• JavaScript in Firefox
• Open a new tab → type about: config in the address bar.
• Then you will find the warning dialog.
• Select I’ll be careful, I promise!
• Then you will find the list of configure options in the
browser.
• In the search bar, type javascript.enabled.
• There you will find the option to enable or disable
javascript by right-clicking on the value of that option →
select toggle.
JavaScript Editor and
Extension
Use Notepad to write the code
Save the document using .html (if embedded
JavaScript)
Save document with .js (if external
JavaScript)
Run the code in brower
JavaScript - Placement
in HTML File
• There is a flexibility given to include JavaScript code anywhere
in an HTML document.
• However the most preferred ways to include JavaScript in
an HTML file are as follows −
• Script in <head>...</head> section.
• Script in <body>...</body> section.
• Script in <body>...</body> and <head>...</head> sections.
• Script in an external file and then include in
<head>...</head> section.
JavaScript in <head>...</head>
section
<html>
<head>
<script type="text/javascript">
<!-- function sayHello()
{ alert("Hello World") }
//--> </script>
</head>
<body>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
• This code will produce the following results −
JavaScript in <body>...</body>
section
<html>
<head> </head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<p>This is web page body </p>
</body>
</html>
• This code will produce the following results
−
Hello World
This is web page body
JavaScript in <body> and
<head>
<html>
<head>
<script type="text/javascript">
<!-- function sayHello()
{ alert("Hello World") } //-->
</script>
</head>
<body>
<script type="text/javascript">
<!-- document.write("Hello World") //-->
</script>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body> </html>
• This code will produce the following result −
JavaScript in External
File
• HTML File
<html>
<head>
<script type="text/javascript" src="filename.js" >
</script>
</head>
<body> ....... </body>
</html>
• JavaScript File – filename.js
function sayHello()
{ alert("Hello World") }
The First
Script
20
first-script.html
<html>
<body>
<script type="text/javascript">
alert('Hello JavaScript!');
</script>
</body>
</html>
Another Small
Example
21
small-example.html
<html>
<body>
<script type="text/javascript">
document.write('JavaScript rulez!');
</script>
</body>
</html>
Using JavaScript
Code
• The JavaScript code can be placed in:
• <script> tag in the head
• <script> tag in the body – not
recommended
• External files, linked via <script> tag the
head
• Files usually have .js extension
• Highly recommended
• The .js files get cached by the browser
22
<script src="scripts.js" type="text/javscript">
<!– code placed here will not be executed! -->
</script>
JavaScript – When is
Executed?
• JavaScript code is executed during the page loading or when
the browser fires an event
• All statements are executed at page loading
• Some statements just define functions that can be called later
• Function calls or code can be attached as "event handlers" via
tag attributes
• Executed when the event is fired by the browser
23
<img src="logo.gif" onclick="alert('clicked!')" />
<html>
<head>
<script type="text/javascript">
function test (message)
{
alert(message);
}
</script>
</head>
<body>
<img src="logo.gif"
onclick="test('clicked!')" />
</body>
</html>
Calling a JavaScript Function
from Event Handler – Example
image-onclick.html
24
Using External Script
Files
•Using external script files:
25
<html>
<head>
<script src="sample.js" type="text/javascript">
</script>
</head>
<body>
<button onclick="sample()" value="Call JavaScript
function from sample.js" />
</body>
</html>
•External JavaScript file:
function sample() {
alert('Hello from sample.js!')
}
external-JavaScript.html
sample.js
The <script> tag is always empty.
Data
Types
• JavaScript data types:
• Numbers (integer, floating-point)
• Boolean (true / false)
• String type – string of characters
• Arrays
26
var myName = "You can use both single or double
quotes for strings";
var my_array = [1, 5.3, "aaa"];
• Associative arrays (hash tables)
var my_hash = {a:2, b:3, c:"text"};
Everything is
Object
27
var arr = [1,3,4];
alert (arr.length); // shows 3
arr.push(7); // appends 7 to end of array
alert (arr[3]); // shows 7
• Every variable can be considered as object
• For example strings and arrays have member functions:
objects.html
var test = "some string";
alert(test[7]); // shows letter 'r'
alert(test.charAt(5)); // shows letter 's'
alert("test".charAt(1)); //shows letter 'e'
alert("test".substring(1,3)); //shows 'es'
String Operations
• The + operator joins
strings
• What is "9" + 9?
• Converting string to number:
28
string1 = "fat ";
string2 = "cats";
alert(string1 + string2); // fat cats
alert("9" + 9); // 99
alert(parseInt("9") + 9); // 18
Arrays Operations and
Properties
•Declaring new empty
array:
•Declaring an array holding few elements:
•Appending an element / getting the last
element:
•Reading the number of elements (array length):
•Finding element's index in the
array:
29
var arr = new Array();
var arr = [1, 2, 3, 4, 5];
arr.push(3);
var element = arr.pop();
arr.length;
arr.indexOf(1);
Standard Popup
Boxes
• Alert box with text and [OK] button
• Just a message shown in a dialog box:
• Confirmation box
• Contains text, [OK] button and [Cancel] button:
• Prompt box
• Contains text, input field with default value:
30
alert("Some text here");
confirm("Are you sure?");
prompt ("enter amount", 10);
JavaScript Variables
<script
type="text/javascript">
<!--
var name = "Ali";
var money;
money = 2000.50;
//-->
</script>
Sum of Numbers –
Example
sum-of-numbers.html
32
<html>
<head>
<title>JavaScript Demo</title>
<script type="text/javascript">
function calcSum() {
value1 =
parseInt(document.mainForm.textBox1.value);
value2 =
parseInt(document.mainForm.textBox2.value);
sum = value1 + value2;
document.mainForm.textBoxSum.value = sum;
}
</script>
</head>
Sum of Numbers – Example
(2)
sum-of-numbers.html (cont.)
33
<body>
<form name="mainForm">
<input type="text" name="textBox1" /> <br/>
<input type="text" name="textBox2" /> <br/>
<input type="button" value="Process"
onclick="javascript: calcSum()" />
<input type="text" name="textBoxSum"
readonly="readonly"/>
</form>
</body>
</html>
JavaScript Prompt –
Example
prompt.html
34
price = prompt("Enter the price", "10.00");
alert('Price + VAT = ' + price * 1.2);
JavaScript - Operators
• Arithmetic Operators
• Comparison Operators
• Logical (or Relational) Operators
• Assignment Operators
• Conditional (or ternary)
Operators
Symbol Meaning
>Greater than
<Less than
>= Greater than or equal to
<= Less than or equal to
== Equal
!= Not equal
Conditional Statement (if)
36
unitPrice = 1.30;
if (quantity > 100) {
unitPrice = 1.20;
}
Switch Statement
• The switch statement works like in
C#:
37
switch (variable) {
case 1:
// do something
break;
case 'a':
// do something else
break;
case 3.14:
// another code
break;
default:
// something completely different
}
switch-statements.html
Switch case
Example
Loop
s
• Like in C#
• for loop
• while loop
• do … while
loop
39
var counter;
for (counter=0; counter<4; counter++)
{
alert(counter);
}
while (counter < 5)
{
alert(++counter);
}
loops.html
While-loop
Example
• <html>
• <body>
• <script type="text/javascript">
• <!-- var count = 0;
• document.write("Starting Loop ");
• while (count < 10){
• document.write("Current Count : " + count + "<br />");
count++; }
• document.write("Loop stopped!");
• //--> </script>
• <p>Set the variable to different value and then
try...</p>
</body> </html>
Functions
• Code structure – splitting code into parts
• Data comes in, processed, result returned
41
function average(a, b, c)
{
var total;
total = a+b+c;
return total/3;
}
Parameters come in
here.
Declaring variables
is optional. Type is
never declared.
Value returned
here.
Function Arguments & Return
Value
• Functions are not required to return a value
• When calling function it is not obligatory to specify all of its
arguments
•The function has access to all the arguments passed
via arguments array
42
function sum() {
var sum = 0;
for (var i = 0; i < arguments.length; i ++)
sum += parseInt(arguments[i]);
return sum;
}
alert(sum(1, 2, 4));
functions-demo.html
JavaScript Function
Syntax
• function name(parameter1, parameter2, parameter3) {
code to be executed
}
• var x = myFunction(4, 3); // Function is called, return value
will end up in x
function myFunction(a, b) {
// Function returns the product of a
return a * b;
and b
}
Outlin
e
JavaScript: Overview of JavaScript, using JS in an HTML
(Embedded, External), Data types, Control Structures,
Arrays, Functions and Scopes, Objects in JS,
DOM: DOM levels, DOM Objects and their properties and
methods, Manipulating DOM,
JQuery: Introduction to JQuery, Loading JQuery, Selecting
elements, changing styles, creating elements, appending
elements, removing elements, handling events.
DOM- Document Object
Mode
• When a web page is loaded, the browser creates a Document
Object Model of the page.
• The HTML DOM model is constructed as a tree of Objects:
Benefits of DOM to JavaScript
• With the object model, JavaScript gets all the power it needs
to create dynamic HTML:
• JavaScript can change all the HTML elements in the page
• JavaScript can change all the HTML attributes in the page
• JavaScript can change all the CSS styles in the page
• JavaScript can remove existing HTML elements and attributes
• JavaScript can add new HTML elements and attributes
• JavaScript can react to all existing HTML events in the page
• JavaScript can create new HTML events in the page
What is the
DOM?
• The DOM is a W3C (World Wide Web Consortium) standard.
• The DOM defines a standard for accessing documents:
• "The W3C Document Object Model (DOM) is a platform and
language-neutral interface that allows programs and scripts
to dynamically access and update the content, structure, and
style of a document.“
• The W3C DOM standard is separated into 3 different parts:
1. Core DOM - standard model for all document types
2. XML DOM - standard model for XML documents
3. HTML DOM - standard model for HTML documents
DOM Levels
• DOM Level 1
• DOM Level 2
• DOM Level 3
• For More details regarding DOM levels click on below site.
https://developer.mozilla.org/fr/docs/DOM_Levels
DOM Level 1
• The DOM Level 1 specification is separated into two parts:
1. Core and
2. HTML.
• Core Level 1 provides a low-level set of fundamental
interfaces that can represent any structured document, as
well as defining extended interfaces for representing an XML
document.
• HTML Level 1 provides additional, higher-level interfaces that
are used with the fundamental interfaces defined in Core
Level 1 to provide a more convenient view of an HTML
document. Interfaces introduced in DOM1 include, among
others, the Document, Node, Attr, Element, and Text
interfaces.
DOM Level 2
• The DOM Level 2 specification contains six
different specifications:
• The DOM2 Core,
• Views,
• Events,
• Style,
• Traversal and Range, and
• the DOM2 HTML. Most of the DOM Level 2 is supported in
Mozilla.
DOM Level 2
Specification Description
DOM Level 2 Core
helps the programs and scripts to access and update
the content and structure of document dynamically
DOM Level 2 Views
allows programs and scripts to dynamically access and
update the content of an HTML or XML document
DOM Level 2 Events
provides a generic event system to programs and
scripts
DOM Level 2 Style
allows programs and scripts to dynamically access and
update the content of style sheets
DOM Level 2
Traversal and Range
allows programs and scripts to dynamically
traverse and identify a range of content in a
document
DOM Level 2 HTML
allows programs and scripts to dynamically access and
update the content and structure of HTML 4.01 and
XHTML 1.0 documents
DOM Level 3
• The DOM Level 3 specification contains five
different specifications:
• The DOM3 Core,
• Load and Save,
• Validation,
• Events, and
• XPath.
DOM Level 3
Specification Description
DOM Level 3 Core
allows programs and scripts to dynamically access and
update the content, structure, and document style
DOM Level 3 Load
and Save
allows programs and scripts to dynamically load the
content of an XML document into a DOM document
DOM Level 3
Validation
allows programs and scripts to dynamically update the
content and structure of documents and ensures that
the document remains valid
DOM Objects and their
properties and
methods
• In the DOM, all HTML elements are defined as objects.
• The programming interface is the properties and methods of
each object.
• HTML DOM properties are values (of HTML Elements) that
you can set or change.
• HTML DOM methods are actions you can perform (on HTML
Elements). A method is an action you can do (like add or
deleting an HTML element).
DOM Example 1
• The following example changes the content (the innerHTML) of
the <p> element with id="demo":
• Example
• <html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>
</body>
</html>
• In the example above, getElementById is a method, while
innerHTML is a property.
Output
getElementById & innerHTML
• The getElementById Method
• The most common way to access an HTML element is to use
the id of the element.
• In the example above the getElementById method used
id="demo" to find the element.
• The innerHTML Property
• The easiest way to get the content of an element is by using
the innerHTML property.
• The innerHTML property is useful for getting or replacing the
content of HTML elements.
• The innerHTML property can be used to get or change any
HTML element, including <html> and <body>.
Finding HTML Elements
Method Description
document.getElementById(id) Find an element by element id
document.getElementsByTagName(name) Find elements by tag name
document.getElementsByClassName(name) Find elements by class name
Changing HTML Elements
Method Description
element.innerHTML = new html content
Change the inner HTML of an
element
element.attribute = new value
Change the attribute value of an
HTML element
element.setAttribute(attribute, value)
Change the attribute value of an
HTML element
element.style.property = new style
Change the style of an HTML
element
Adding and Deleting Elements
Method Description
document.createElement(element) Create an HTML element
document.removeChild(element) Remove an HTML element
document.appendChild(element) Add an HTML element
document.replaceChild(element) Replace an HTML element
document.write(text) Write into the HTML output stream
Adding Events Handlers
Method Description
document.getElementById(id).onclick
= function(){code}
Adding event
handler code to an
onclick event
Finding HTML Objects
Property Description DOM
document.baseURI
Returns the absolute base URI of the
document
3
document.body Returns the <body> element 1
document.cookie Returns the document's cookie 1
document.doctype Returns the document's doctype 3
document.forms Returns all <form> elements 1
document.head Returns the <head> element 3
document.images Returns all <img> elements 1
Changing HTML
Content
• Example
<html> <body>
<h2>JavaScript can Change HTML</h2>
<p id="p1">Hello World!</p>
<script>
document.getElementById("p1").innerHTML = "New text!";
</script>
<p>The paragraph above was changed by a script.</p>
</body> </html>
• Output
JavaScript can Change HTML
New text!
The paragraph above was changed by a script.
Changing the Value of an Attribute
• Example
<html><body>
<img id="image" src="smiley.gif" width="160" height="120">
<script>
document.getElementById("image").src = "landscape.jpg";
</script>
<p>The original image was smiley.gif, but the script changed it to
landscape.jpg</p>
</body></html>
• Output
Outlin
e
JavaScript: Overview of JavaScript, using JS in an HTML
(Embedded, External), Data types, Control Structures,
Arrays, Functions and Scopes, Objects in JS,
DOM: DOM levels, DOM Objects and their properties and
methods, Manipulating DOM,
JQuery: Introduction to JQuery, Loading JQuery, Selecting
elements, changing styles, creating elements, appending
elements, removing elements, handling events.
jQuery - Introduction
• jQuery is a JavaScript Library.
• jQuery greatly simplifies JavaScript programming.
• jQuery is a lightweight
• 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
Adding jQuery to Your
Web Pages
• There are several ways to start using jQuery on your web
site. You can:
• Download the jQuery library from jQuery.com
• Include jQuery from a CDN, like Google
Downloading
jQuery
• There are two versions of jQuery available for downloading:
• Production version - this is for your live website because it has
been minified and compressed
• Development version - this is for testing and development
• Both versions can be downloaded from jQuery.com.
• The jQuery library is a single JavaScript file, and you
reference it with the HTML <script> tag (notice that the
<script> tag should be inside the <head> section):
<head>
<script src="jquery-3.2.1.min.js"></script>
</head>
• Tip: Place the downloaded file in the same directory as the
pages where you wish to use it.
jQuery
CDN
• If you don't want to download and host jQuery yourself, you
can include it from a CDN (Content Delivery Network).
• Both Google and Microsoft host jQuery.
• To use jQuery from Google or Microsoft, use one of the following:
• Google CDN:
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
</head>
jQuery
Syntax
• With jQuery you select (query) HTML elements and
perform "actions" on them.
• syntax :
• $(selector).action()
• A $ sign to define/access jQuery
• A (selector) to "query (or find)" HTML elements
• A jQuery action() to be performed on the element(s)
• Examples:
• $(this).hide() - hides the current element.
• $("p").hide() - hides all <p> elements.
• $(".test").hide() - hides all elements with class="test".
• $("#test").hide() - hides the element with id="test".
jQuery
Selectors-Selecting
elements
• jQuery selectors allow you 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. It's based on the existing CSS
Selectors, and in addition, it has some own custom selectors.
• All selectors in jQuery start with the dollar sign and
parentheses: $().
The element Selector
• The jQuery element selector selects elements based on the
element name.
• You can select all <p> elements on a page like this:
• $("p")
• Example
• When a user clicks on a button, all <p> elements will be
hidden:
• $(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
The #id Selector
• The jQuery #id selector uses the id attribute of an HTML tag to find
the specific element.
• An id should be unique within a page, so you should use the #id
selector when you want to find a single, unique element.
• To find an element with a specific id, write a hash
character, followed by the id of the HTML element:
• $("#test")
• Example
• When a user clicks on a button, the element with id="test" will be
hidden:
• $(document).ready(function(){
$("button").click(function(){
$("#test").hide();
});
});
jQuery css() Method- Changing
Style
• jQuery css() Method
• The css() method sets or returns one or more style
properties for the selected elements.
•Return a CSS Property
• To return the value of a specified CSS property, use the
following syntax:
• css("propertyname");
•Set a CSS Property
• To set a specified CSS property, use the following
syntax:
• css("propertyname","value");
Changing Style-
Return a CSS Property
Example
<html><head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></sc
ript>
<script>
$(document).ready(function(){
$("button").click(function(){
alert("Background color = " + $("p").css("background-color"));
});
});
</script>
</head><body>
<p style="background-color:#ff0000">This is a paragraph.</p>
<button>Return background-color of p</button>
</body></html>
Changing Style-
Return a CSS Property Example
o/p
Output of Previous Code
Changing Style-
Set a CSS Property Example
<html><head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").css("background-color", "yellow");
});
});
</script>
</head>
<body>
<p style="background-color:#ff0000">This is a paragraph.</p>
<button>Set background-color of p</button>
</body></html>
Changing Style-
Set a CSS Property Example
o/p
Output of Previous Code
After clicking on button
jQuery - Add Elements
• We will look at four jQuery methods that are used to add new
content:
• append() - Inserts content at the end of the selected
elements
• prepend() - Inserts content at the beginning of the
selected elements
• after() - Inserts content after the selected elements
• before() - Inserts content before the selected elements
jQuery append() Method-
Example
<html><head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></scrip
t>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("ol").append("<li> List item 3 </li>");
}); }); </script>
</head>
<body>
<ol>
<li>List item 1</li>
<li>List item 2</li>
</ol>
<button id="btn1"> Append list items </button>
</body></html>
After Clicking on button
jQuery - Remove Elements
• Remove Elements/Content
• To remove elements and content, there are mainly two jQuery
methods:
• remove() - Removes the selected element (and its
child elements)
• empty() - Removes the child elements from the
selected element
jQuery remove() Method-
Example
• <html > <head>
• <script
src="https://code.jquery.com/jquery-1.10.2.js">
</script>
• </head>
• <body>
• <p>Hello</p>
• how are you?
• <button>Remove </button>
• <script>
• $( "button" ).click(function() {
• $( "p" ).remove();
• });
• </script>
• </body></html>
After Clicking on button
References
• https://www.slideshare.net/rakhithota/js-ppt
• https://www.tutorialspoint.com/javascript/javascript_quic
k_guide.htm
• https://www.w3schools.com/js
• https://www.w3schools.com/js/js_htmldom.asp
• https://developer.mozilla.org/fr/docs/DOM_Levels
• https://codescracker.com/js/js-dom-levels.htm
• https://www.w3schools.com/jquery/jquery_get_started.a
sp
• https://www.w3schools.com/jquery/jquery_css.asp
• https://www.w3schools.com/jquery/jquery_dom_add.asp

More Related Content

PDF
Wt unit 2 ppts client side technology
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 
PDF
Wt unit 2 ppts client sied technology
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 
PPTX
JavaScriptL18 [Autosaved].pptx
VivekBaghel30
 
PPTX
Java script
Jay Patel
 
PPTX
Javascript
Sun Technlogies
 
PPTX
Final Java-script.pptx
AlkanthiSomesh
 
PPTX
Basics of Java Script (JS)
Ajay Khatri
 
PPTX
Java script
Ravinder Kamboj
 
Wt unit 2 ppts client side technology
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 
Wt unit 2 ppts client sied technology
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 
JavaScriptL18 [Autosaved].pptx
VivekBaghel30
 
Java script
Jay Patel
 
Javascript
Sun Technlogies
 
Final Java-script.pptx
AlkanthiSomesh
 
Basics of Java Script (JS)
Ajay Khatri
 
Java script
Ravinder Kamboj
 

Similar to WT UNIT 2 presentation :client side technologies JavaScript And Dom (20)

PPTX
Introduction to JavaScript
Marlon Jamera
 
PPTX
Wt unit 5
team11vgnt
 
PDF
Intro JavaScript
koppenolski
 
PPT
Js mod1
VARSHAKUMARI49
 
PPTX
Unit III.pptx IT3401 web essentials presentatio
lakshitakumar291
 
PPTX
unit4 wp.pptxjvlbpuvghuigv8ytg2ugvugvuygv
utsavsd11
 
PDF
Build a game with javascript (may 21 atlanta)
Thinkful
 
PPTX
jQuery
PumoTechnovation
 
PPT
8486477.ppt
logesswarisrinivasan
 
PPTX
e-suap - client technologies- english version
Sabino Labarile
 
PPTX
Internet protocol second unit IIPPT.pptx
ssuser92282c
 
PPTX
Js placement
Sireesh K
 
PPTX
BITM3730 10-17.pptx
MattMarino13
 
PPTX
Java script writing javascript
Jesus Obenita Jr.
 
PDF
Client sidescripting javascript
Selvin Josy Bai Somu
 
PDF
IT2255 Web Essentials - Unit III Client-Side Processing and Scripting
pkaviya
 
PDF
JS BASICS JAVA SCRIPT SCRIPTING
Arulkumar
 
PPT
javascript-basics.ppt
ahmadfaisal744721
 
PDF
Unit 4(it workshop)
Dr.Lokesh Gagnani
 
PPT
Java script
Soham Sengupta
 
Introduction to JavaScript
Marlon Jamera
 
Wt unit 5
team11vgnt
 
Intro JavaScript
koppenolski
 
Unit III.pptx IT3401 web essentials presentatio
lakshitakumar291
 
unit4 wp.pptxjvlbpuvghuigv8ytg2ugvugvuygv
utsavsd11
 
Build a game with javascript (may 21 atlanta)
Thinkful
 
e-suap - client technologies- english version
Sabino Labarile
 
Internet protocol second unit IIPPT.pptx
ssuser92282c
 
Js placement
Sireesh K
 
BITM3730 10-17.pptx
MattMarino13
 
Java script writing javascript
Jesus Obenita Jr.
 
Client sidescripting javascript
Selvin Josy Bai Somu
 
IT2255 Web Essentials - Unit III Client-Side Processing and Scripting
pkaviya
 
JS BASICS JAVA SCRIPT SCRIPTING
Arulkumar
 
javascript-basics.ppt
ahmadfaisal744721
 
Unit 4(it workshop)
Dr.Lokesh Gagnani
 
Java script
Soham Sengupta
 
Ad

Recently uploaded (20)

PPT
SCOPE_~1- technology of green house and poyhouse
bala464780
 
PDF
EVS+PRESENTATIONS EVS+PRESENTATIONS like
saiyedaqib429
 
PDF
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
PDF
Traditional Exams vs Continuous Assessment in Boarding Schools.pdf
The Asian School
 
PDF
flutter Launcher Icons, Splash Screens & Fonts
Ahmed Mohamed
 
PDF
dse_final_merit_2025_26 gtgfffffcjjjuuyy
rushabhjain127
 
PDF
Activated Carbon for Water and Wastewater Treatment_ Integration of Adsorptio...
EmilianoRodriguezTll
 
PPTX
Simulation of electric circuit laws using tinkercad.pptx
VidhyaH3
 
PDF
오픈소스 LLM, vLLM으로 Production까지 (Instruct.KR Summer Meetup, 2025)
Hyogeun Oh
 
PDF
LEAP-1B presedntation xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
hatem173148
 
PPT
Ppt for engineering students application on field effect
lakshmi.ec
 
PPTX
easa module 3 funtamental electronics.pptx
tryanothert7
 
PDF
Software Testing Tools - names and explanation
shruti533256
 
PPTX
AgentX UiPath Community Webinar series - Delhi
RohitRadhakrishnan8
 
PPTX
Module2 Data Base Design- ER and NF.pptx
gomathisankariv2
 
PPTX
EE3303-EM-I 25.7.25 electrical machines.pptx
Nagen87
 
PPTX
Victory Precisions_Supplier Profile.pptx
victoryprecisions199
 
PPTX
Chapter_Seven_Construction_Reliability_Elective_III_Msc CM
SubashKumarBhattarai
 
PDF
Top 10 read articles In Managing Information Technology.pdf
IJMIT JOURNAL
 
PDF
B.Tech Data Science Program (Industry Integrated ) Syllabus
rvray078
 
SCOPE_~1- technology of green house and poyhouse
bala464780
 
EVS+PRESENTATIONS EVS+PRESENTATIONS like
saiyedaqib429
 
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
Traditional Exams vs Continuous Assessment in Boarding Schools.pdf
The Asian School
 
flutter Launcher Icons, Splash Screens & Fonts
Ahmed Mohamed
 
dse_final_merit_2025_26 gtgfffffcjjjuuyy
rushabhjain127
 
Activated Carbon for Water and Wastewater Treatment_ Integration of Adsorptio...
EmilianoRodriguezTll
 
Simulation of electric circuit laws using tinkercad.pptx
VidhyaH3
 
오픈소스 LLM, vLLM으로 Production까지 (Instruct.KR Summer Meetup, 2025)
Hyogeun Oh
 
LEAP-1B presedntation xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
hatem173148
 
Ppt for engineering students application on field effect
lakshmi.ec
 
easa module 3 funtamental electronics.pptx
tryanothert7
 
Software Testing Tools - names and explanation
shruti533256
 
AgentX UiPath Community Webinar series - Delhi
RohitRadhakrishnan8
 
Module2 Data Base Design- ER and NF.pptx
gomathisankariv2
 
EE3303-EM-I 25.7.25 electrical machines.pptx
Nagen87
 
Victory Precisions_Supplier Profile.pptx
victoryprecisions199
 
Chapter_Seven_Construction_Reliability_Elective_III_Msc CM
SubashKumarBhattarai
 
Top 10 read articles In Managing Information Technology.pdf
IJMIT JOURNAL
 
B.Tech Data Science Program (Industry Integrated ) Syllabus
rvray078
 
Ad

WT UNIT 2 presentation :client side technologies JavaScript And Dom

  • 1. Unit II- Client Side Technologies: JavaScript and DOM
  • 2. Outlin e , appending elements, removing elements, handling events.
  • 3. JavaScript- Outline • using JS in an HTML (Embedded, External), • Data types, • Control Structures, • Arrays, • Functions • Objects • Scopes
  • 4. Overview of JavaScript, • JavaScript is one of the 3 languages all web developers must learn: • 1. HTML to define the content of web pages • 2. CSS to specify the layout of web pages • 3. JavaScript to program the behavior of web pages • JavaScript is a very powerful client-side scripting language. • Javascript is a dynamic computer programming language. •
  • 5. JavaScript • JavaScript is a front-end scripting language developed by Netscape for dynamic content • Lightweight, but with limited capabilities • Can be used as object-oriented language • Client-side technology • Embedded in your HTML page • Interpreted by the Web browser • Simple and flexible • Powerful to manipulate the DOM 6
  • 6. JavaScript Advantages • JavaScript allows interactivity such as: • Implementing form validation • React to user actions, e.g. handle keys • Changing an image on moving mouse over it • Sections of a page appearing and disappearing • Content loading and changing dynamically • Performing complex calculations • Custom HTML controls, e.g. scrollable table • Implementing AJAX functionality 7
  • 7. What Can JavaScript Do? • Can handle events • Can read and write HTML elements • Can validate form data • Can access / modify browser cookies • Can detect the user’s browser and OS • Can be used as object-oriented language • Can handle exceptions • Can perform asynchronous server calls (AJAX) 8
  • 9. JavaScript Syntax • JavaScript can be implemented using <script>... </script> HTML tags in a web page. • Place the <script> tags, within the <head> tags. • Syntax: • <script language="javascript" type="text/javascript"> • JavaScript code • </script>
  • 10. JavaScript Syntax • Example: <html> <body> <script language="javascript" type="text/javascript"> <!-- document.write("Hello World!") //--> </script> </body> </html> • The comment ends with a "//-->". Here "//" signifies a comment in JavaScript • Output Hello World!
  • 11. JavaScript Syntax • The JavaScript syntax is similar to C# and Java • Operators (+, *, =, !=, &&, ++, …) • Variables (typeless) • Conditional statements (if, else) • Loops (for, while) • Arrays (my_array[]) and associative arrays (my_array['abc']) • Functions (can return value) • Function variables (like the C# delegates) 12
  • 12. Enabling JavaScript in Browsers • JavaScript in Firefox • Open a new tab → type about: config in the address bar. • Then you will find the warning dialog. • Select I’ll be careful, I promise! • Then you will find the list of configure options in the browser. • In the search bar, type javascript.enabled. • There you will find the option to enable or disable javascript by right-clicking on the value of that option → select toggle.
  • 13. JavaScript Editor and Extension Use Notepad to write the code Save the document using .html (if embedded JavaScript) Save document with .js (if external JavaScript) Run the code in brower
  • 14. JavaScript - Placement in HTML File • There is a flexibility given to include JavaScript code anywhere in an HTML document. • However the most preferred ways to include JavaScript in an HTML file are as follows − • Script in <head>...</head> section. • Script in <body>...</body> section. • Script in <body>...</body> and <head>...</head> sections. • Script in an external file and then include in <head>...</head> section.
  • 15. JavaScript in <head>...</head> section <html> <head> <script type="text/javascript"> <!-- function sayHello() { alert("Hello World") } //--> </script> </head> <body> <input type="button" onclick="sayHello()" value="Say Hello" /> </body> </html> • This code will produce the following results −
  • 16. JavaScript in <body>...</body> section <html> <head> </head> <body> <script type="text/javascript"> <!-- document.write("Hello World") //--> </script> <p>This is web page body </p> </body> </html> • This code will produce the following results − Hello World This is web page body
  • 17. JavaScript in <body> and <head> <html> <head> <script type="text/javascript"> <!-- function sayHello() { alert("Hello World") } //--> </script> </head> <body> <script type="text/javascript"> <!-- document.write("Hello World") //--> </script> <input type="button" onclick="sayHello()" value="Say Hello" /> </body> </html> • This code will produce the following result −
  • 18. JavaScript in External File • HTML File <html> <head> <script type="text/javascript" src="filename.js" > </script> </head> <body> ....... </body> </html> • JavaScript File – filename.js function sayHello() { alert("Hello World") }
  • 21. Using JavaScript Code • The JavaScript code can be placed in: • <script> tag in the head • <script> tag in the body – not recommended • External files, linked via <script> tag the head • Files usually have .js extension • Highly recommended • The .js files get cached by the browser 22 <script src="scripts.js" type="text/javscript"> <!– code placed here will not be executed! --> </script>
  • 22. JavaScript – When is Executed? • JavaScript code is executed during the page loading or when the browser fires an event • All statements are executed at page loading • Some statements just define functions that can be called later • Function calls or code can be attached as "event handlers" via tag attributes • Executed when the event is fired by the browser 23 <img src="logo.gif" onclick="alert('clicked!')" />
  • 23. <html> <head> <script type="text/javascript"> function test (message) { alert(message); } </script> </head> <body> <img src="logo.gif" onclick="test('clicked!')" /> </body> </html> Calling a JavaScript Function from Event Handler – Example image-onclick.html 24
  • 24. Using External Script Files •Using external script files: 25 <html> <head> <script src="sample.js" type="text/javascript"> </script> </head> <body> <button onclick="sample()" value="Call JavaScript function from sample.js" /> </body> </html> •External JavaScript file: function sample() { alert('Hello from sample.js!') } external-JavaScript.html sample.js The <script> tag is always empty.
  • 25. Data Types • JavaScript data types: • Numbers (integer, floating-point) • Boolean (true / false) • String type – string of characters • Arrays 26 var myName = "You can use both single or double quotes for strings"; var my_array = [1, 5.3, "aaa"]; • Associative arrays (hash tables) var my_hash = {a:2, b:3, c:"text"};
  • 26. Everything is Object 27 var arr = [1,3,4]; alert (arr.length); // shows 3 arr.push(7); // appends 7 to end of array alert (arr[3]); // shows 7 • Every variable can be considered as object • For example strings and arrays have member functions: objects.html var test = "some string"; alert(test[7]); // shows letter 'r' alert(test.charAt(5)); // shows letter 's' alert("test".charAt(1)); //shows letter 'e' alert("test".substring(1,3)); //shows 'es'
  • 27. String Operations • The + operator joins strings • What is "9" + 9? • Converting string to number: 28 string1 = "fat "; string2 = "cats"; alert(string1 + string2); // fat cats alert("9" + 9); // 99 alert(parseInt("9") + 9); // 18
  • 28. Arrays Operations and Properties •Declaring new empty array: •Declaring an array holding few elements: •Appending an element / getting the last element: •Reading the number of elements (array length): •Finding element's index in the array: 29 var arr = new Array(); var arr = [1, 2, 3, 4, 5]; arr.push(3); var element = arr.pop(); arr.length; arr.indexOf(1);
  • 29. Standard Popup Boxes • Alert box with text and [OK] button • Just a message shown in a dialog box: • Confirmation box • Contains text, [OK] button and [Cancel] button: • Prompt box • Contains text, input field with default value: 30 alert("Some text here"); confirm("Are you sure?"); prompt ("enter amount", 10);
  • 30. JavaScript Variables <script type="text/javascript"> <!-- var name = "Ali"; var money; money = 2000.50; //--> </script>
  • 31. Sum of Numbers – Example sum-of-numbers.html 32 <html> <head> <title>JavaScript Demo</title> <script type="text/javascript"> function calcSum() { value1 = parseInt(document.mainForm.textBox1.value); value2 = parseInt(document.mainForm.textBox2.value); sum = value1 + value2; document.mainForm.textBoxSum.value = sum; } </script> </head>
  • 32. Sum of Numbers – Example (2) sum-of-numbers.html (cont.) 33 <body> <form name="mainForm"> <input type="text" name="textBox1" /> <br/> <input type="text" name="textBox2" /> <br/> <input type="button" value="Process" onclick="javascript: calcSum()" /> <input type="text" name="textBoxSum" readonly="readonly"/> </form> </body> </html>
  • 33. JavaScript Prompt – Example prompt.html 34 price = prompt("Enter the price", "10.00"); alert('Price + VAT = ' + price * 1.2);
  • 34. JavaScript - Operators • Arithmetic Operators • Comparison Operators • Logical (or Relational) Operators • Assignment Operators • Conditional (or ternary) Operators
  • 35. Symbol Meaning >Greater than <Less than >= Greater than or equal to <= Less than or equal to == Equal != Not equal Conditional Statement (if) 36 unitPrice = 1.30; if (quantity > 100) { unitPrice = 1.20; }
  • 36. Switch Statement • The switch statement works like in C#: 37 switch (variable) { case 1: // do something break; case 'a': // do something else break; case 3.14: // another code break; default: // something completely different } switch-statements.html
  • 38. Loop s • Like in C# • for loop • while loop • do … while loop 39 var counter; for (counter=0; counter<4; counter++) { alert(counter); } while (counter < 5) { alert(++counter); } loops.html
  • 39. While-loop Example • <html> • <body> • <script type="text/javascript"> • <!-- var count = 0; • document.write("Starting Loop "); • while (count < 10){ • document.write("Current Count : " + count + "<br />"); count++; } • document.write("Loop stopped!"); • //--> </script> • <p>Set the variable to different value and then try...</p> </body> </html>
  • 40. Functions • Code structure – splitting code into parts • Data comes in, processed, result returned 41 function average(a, b, c) { var total; total = a+b+c; return total/3; } Parameters come in here. Declaring variables is optional. Type is never declared. Value returned here.
  • 41. Function Arguments & Return Value • Functions are not required to return a value • When calling function it is not obligatory to specify all of its arguments •The function has access to all the arguments passed via arguments array 42 function sum() { var sum = 0; for (var i = 0; i < arguments.length; i ++) sum += parseInt(arguments[i]); return sum; } alert(sum(1, 2, 4)); functions-demo.html
  • 42. JavaScript Function Syntax • function name(parameter1, parameter2, parameter3) { code to be executed } • var x = myFunction(4, 3); // Function is called, return value will end up in x function myFunction(a, b) { // Function returns the product of a return a * b; and b }
  • 43. Outlin e JavaScript: Overview of JavaScript, using JS in an HTML (Embedded, External), Data types, Control Structures, Arrays, Functions and Scopes, Objects in JS, DOM: DOM levels, DOM Objects and their properties and methods, Manipulating DOM, JQuery: Introduction to JQuery, Loading JQuery, Selecting elements, changing styles, creating elements, appending elements, removing elements, handling events.
  • 44. DOM- Document Object Mode • When a web page is loaded, the browser creates a Document Object Model of the page. • The HTML DOM model is constructed as a tree of Objects:
  • 45. Benefits of DOM to JavaScript • With the object model, JavaScript gets all the power it needs to create dynamic HTML: • JavaScript can change all the HTML elements in the page • JavaScript can change all the HTML attributes in the page • JavaScript can change all the CSS styles in the page • JavaScript can remove existing HTML elements and attributes • JavaScript can add new HTML elements and attributes • JavaScript can react to all existing HTML events in the page • JavaScript can create new HTML events in the page
  • 46. What is the DOM? • The DOM is a W3C (World Wide Web Consortium) standard. • The DOM defines a standard for accessing documents: • "The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document.“ • The W3C DOM standard is separated into 3 different parts: 1. Core DOM - standard model for all document types 2. XML DOM - standard model for XML documents 3. HTML DOM - standard model for HTML documents
  • 47. DOM Levels • DOM Level 1 • DOM Level 2 • DOM Level 3 • For More details regarding DOM levels click on below site. https://developer.mozilla.org/fr/docs/DOM_Levels
  • 48. DOM Level 1 • The DOM Level 1 specification is separated into two parts: 1. Core and 2. HTML. • Core Level 1 provides a low-level set of fundamental interfaces that can represent any structured document, as well as defining extended interfaces for representing an XML document. • HTML Level 1 provides additional, higher-level interfaces that are used with the fundamental interfaces defined in Core Level 1 to provide a more convenient view of an HTML document. Interfaces introduced in DOM1 include, among others, the Document, Node, Attr, Element, and Text interfaces.
  • 49. DOM Level 2 • The DOM Level 2 specification contains six different specifications: • The DOM2 Core, • Views, • Events, • Style, • Traversal and Range, and • the DOM2 HTML. Most of the DOM Level 2 is supported in Mozilla.
  • 50. DOM Level 2 Specification Description DOM Level 2 Core helps the programs and scripts to access and update the content and structure of document dynamically DOM Level 2 Views allows programs and scripts to dynamically access and update the content of an HTML or XML document DOM Level 2 Events provides a generic event system to programs and scripts DOM Level 2 Style allows programs and scripts to dynamically access and update the content of style sheets DOM Level 2 Traversal and Range allows programs and scripts to dynamically traverse and identify a range of content in a document DOM Level 2 HTML allows programs and scripts to dynamically access and update the content and structure of HTML 4.01 and XHTML 1.0 documents
  • 51. DOM Level 3 • The DOM Level 3 specification contains five different specifications: • The DOM3 Core, • Load and Save, • Validation, • Events, and • XPath.
  • 52. DOM Level 3 Specification Description DOM Level 3 Core allows programs and scripts to dynamically access and update the content, structure, and document style DOM Level 3 Load and Save allows programs and scripts to dynamically load the content of an XML document into a DOM document DOM Level 3 Validation allows programs and scripts to dynamically update the content and structure of documents and ensures that the document remains valid
  • 53. DOM Objects and their properties and methods • In the DOM, all HTML elements are defined as objects. • The programming interface is the properties and methods of each object. • HTML DOM properties are values (of HTML Elements) that you can set or change. • HTML DOM methods are actions you can perform (on HTML Elements). A method is an action you can do (like add or deleting an HTML element).
  • 54. DOM Example 1 • The following example changes the content (the innerHTML) of the <p> element with id="demo": • Example • <html> <body> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = "Hello World!"; </script> </body> </html> • In the example above, getElementById is a method, while innerHTML is a property. Output
  • 55. getElementById & innerHTML • The getElementById Method • The most common way to access an HTML element is to use the id of the element. • In the example above the getElementById method used id="demo" to find the element. • The innerHTML Property • The easiest way to get the content of an element is by using the innerHTML property. • The innerHTML property is useful for getting or replacing the content of HTML elements. • The innerHTML property can be used to get or change any HTML element, including <html> and <body>.
  • 56. Finding HTML Elements Method Description document.getElementById(id) Find an element by element id document.getElementsByTagName(name) Find elements by tag name document.getElementsByClassName(name) Find elements by class name
  • 57. Changing HTML Elements Method Description element.innerHTML = new html content Change the inner HTML of an element element.attribute = new value Change the attribute value of an HTML element element.setAttribute(attribute, value) Change the attribute value of an HTML element element.style.property = new style Change the style of an HTML element
  • 58. Adding and Deleting Elements Method Description document.createElement(element) Create an HTML element document.removeChild(element) Remove an HTML element document.appendChild(element) Add an HTML element document.replaceChild(element) Replace an HTML element document.write(text) Write into the HTML output stream
  • 59. Adding Events Handlers Method Description document.getElementById(id).onclick = function(){code} Adding event handler code to an onclick event
  • 60. Finding HTML Objects Property Description DOM document.baseURI Returns the absolute base URI of the document 3 document.body Returns the <body> element 1 document.cookie Returns the document's cookie 1 document.doctype Returns the document's doctype 3 document.forms Returns all <form> elements 1 document.head Returns the <head> element 3 document.images Returns all <img> elements 1
  • 61. Changing HTML Content • Example <html> <body> <h2>JavaScript can Change HTML</h2> <p id="p1">Hello World!</p> <script> document.getElementById("p1").innerHTML = "New text!"; </script> <p>The paragraph above was changed by a script.</p> </body> </html> • Output JavaScript can Change HTML New text! The paragraph above was changed by a script.
  • 62. Changing the Value of an Attribute • Example <html><body> <img id="image" src="smiley.gif" width="160" height="120"> <script> document.getElementById("image").src = "landscape.jpg"; </script> <p>The original image was smiley.gif, but the script changed it to landscape.jpg</p> </body></html> • Output
  • 63. Outlin e JavaScript: Overview of JavaScript, using JS in an HTML (Embedded, External), Data types, Control Structures, Arrays, Functions and Scopes, Objects in JS, DOM: DOM levels, DOM Objects and their properties and methods, Manipulating DOM, JQuery: Introduction to JQuery, Loading JQuery, Selecting elements, changing styles, creating elements, appending elements, removing elements, handling events.
  • 64. jQuery - Introduction • jQuery is a JavaScript Library. • jQuery greatly simplifies JavaScript programming. • jQuery is a lightweight • 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
  • 65. Adding jQuery to Your Web Pages • 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
  • 66. Downloading jQuery • There are two versions of jQuery available for downloading: • Production version - this is for your live website because it has been minified and compressed • Development version - this is for testing and development • Both versions can be downloaded from jQuery.com. • The jQuery library is a single JavaScript file, and you reference it with the HTML <script> tag (notice that the <script> tag should be inside the <head> section): <head> <script src="jquery-3.2.1.min.js"></script> </head> • Tip: Place the downloaded file in the same directory as the pages where you wish to use it.
  • 67. jQuery CDN • If you don't want to download and host jQuery yourself, you can include it from a CDN (Content Delivery Network). • Both Google and Microsoft host jQuery. • To use jQuery from Google or Microsoft, use one of the following: • Google CDN: <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"> </script> </head>
  • 68. jQuery Syntax • With jQuery you select (query) HTML elements and perform "actions" on them. • syntax : • $(selector).action() • A $ sign to define/access jQuery • A (selector) to "query (or find)" HTML elements • A jQuery action() to be performed on the element(s) • Examples: • $(this).hide() - hides the current element. • $("p").hide() - hides all <p> elements. • $(".test").hide() - hides all elements with class="test". • $("#test").hide() - hides the element with id="test".
  • 69. jQuery Selectors-Selecting elements • jQuery selectors allow you 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. It's based on the existing CSS Selectors, and in addition, it has some own custom selectors. • All selectors in jQuery start with the dollar sign and parentheses: $().
  • 70. The element Selector • The jQuery element selector selects elements based on the element name. • You can select all <p> elements on a page like this: • $("p") • Example • When a user clicks on a button, all <p> elements will be hidden: • $(document).ready(function(){ $("button").click(function(){ $("p").hide(); }); });
  • 71. The #id Selector • The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. • An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element. • To find an element with a specific id, write a hash character, followed by the id of the HTML element: • $("#test") • Example • When a user clicks on a button, the element with id="test" will be hidden: • $(document).ready(function(){ $("button").click(function(){ $("#test").hide(); }); });
  • 72. jQuery css() Method- Changing Style • jQuery css() Method • The css() method sets or returns one or more style properties for the selected elements. •Return a CSS Property • To return the value of a specified CSS property, use the following syntax: • css("propertyname"); •Set a CSS Property • To set a specified CSS property, use the following syntax: • css("propertyname","value");
  • 73. Changing Style- Return a CSS Property Example <html><head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></sc ript> <script> $(document).ready(function(){ $("button").click(function(){ alert("Background color = " + $("p").css("background-color")); }); }); </script> </head><body> <p style="background-color:#ff0000">This is a paragraph.</p> <button>Return background-color of p</button> </body></html>
  • 74. Changing Style- Return a CSS Property Example o/p Output of Previous Code
  • 75. Changing Style- Set a CSS Property Example <html><head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("p").css("background-color", "yellow"); }); }); </script> </head> <body> <p style="background-color:#ff0000">This is a paragraph.</p> <button>Set background-color of p</button> </body></html>
  • 76. Changing Style- Set a CSS Property Example o/p Output of Previous Code After clicking on button
  • 77. jQuery - Add Elements • We will look at four jQuery methods that are used to add new content: • append() - Inserts content at the end of the selected elements • prepend() - Inserts content at the beginning of the selected elements • after() - Inserts content after the selected elements • before() - Inserts content before the selected elements
  • 78. jQuery append() Method- Example <html><head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></scrip t> <script> $(document).ready(function(){ $("#btn1").click(function(){ $("ol").append("<li> List item 3 </li>"); }); }); </script> </head> <body> <ol> <li>List item 1</li> <li>List item 2</li> </ol> <button id="btn1"> Append list items </button> </body></html> After Clicking on button
  • 79. jQuery - Remove Elements • Remove Elements/Content • To remove elements and content, there are mainly two jQuery methods: • remove() - Removes the selected element (and its child elements) • empty() - Removes the child elements from the selected element
  • 80. jQuery remove() Method- Example • <html > <head> • <script src="https://code.jquery.com/jquery-1.10.2.js"> </script> • </head> • <body> • <p>Hello</p> • how are you? • <button>Remove </button> • <script> • $( "button" ).click(function() { • $( "p" ).remove(); • }); • </script> • </body></html> After Clicking on button
  • 81. References • https://www.slideshare.net/rakhithota/js-ppt • https://www.tutorialspoint.com/javascript/javascript_quic k_guide.htm • https://www.w3schools.com/js • https://www.w3schools.com/js/js_htmldom.asp • https://developer.mozilla.org/fr/docs/DOM_Levels • https://codescracker.com/js/js-dom-levels.htm • https://www.w3schools.com/jquery/jquery_get_started.a sp • https://www.w3schools.com/jquery/jquery_css.asp • https://www.w3schools.com/jquery/jquery_dom_add.asp