0% found this document useful (0 votes)
6 views

Ch03 Javascript & jQuery-1

The document provides an overview of JavaScript, highlighting its features as a lightweight, object-oriented programming language used for web development. It discusses the benefits of client-side and server-side programming, introduces JavaScript syntax, data types, and control structures, and provides examples of JavaScript programs. Additionally, it covers event-driven programming and how JavaScript interacts with HTML through events and event handlers.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Ch03 Javascript & jQuery-1

The document provides an overview of JavaScript, highlighting its features as a lightweight, object-oriented programming language used for web development. It discusses the benefits of client-side and server-side programming, introduces JavaScript syntax, data types, and control structures, and provides examples of JavaScript programs. Additionally, it covers event-driven programming and how JavaScript interacts with HTML through events and event handlers.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 100

3.

JAVASCRIPT AND
JQUERY
Prof. Shital Pashankar

Prof. Shital Pashankar


Introduction
• JavaScript is a lightweight object-oriented programming language which is used
by several websites for scripting the web pages.
• JavaScript is an interpreter programming language that enables dynamic
interactive on website read applied to an HTML document.
• it is open and cross-platform.

Prof. Shital Pashankar


Features of Java script
• the JavaScript is an object based scripting language.
• It is lightweight.
• Interpreter based scripting language.
• JavaScript can put dynamic text into an HTML page.
• JavaScript can react to event.
• JavaScript can read and write HTML document.
• JavaScript can be used to validate data. JavaScript is object based language as it
provides predefined objects.

Prof. Shital Pashankar


Why use client-side programming?

PHP already allows us to create dynamic web pages. Why also use client-side
scripting?
• client-side scripting (JavaScript) benefits:
• usability: can modify a page without having to post back to the server (faster UI)
• efficiency: can make small, quick changes to page without waiting for server
• event-driven: can respond to user actions like clicks and key presses

Prof. Shital Pashankar


Why use server-side programming?

• server-side programming (PHP) benefits:


• security: has access to server's private data; client can't see source code
• compatibility: not subject to browser compatibility issues
• power: can write files, open connections to servers, connect to databases, ...

Prof. Shital Pashankar


What is Javascript?

• a lightweight programming language ("scripting language")


• used to make web pages interactive
• insert dynamic text into HTML (ex: user name)
• react to events (ex: page load user click)
• get information about a user's computer (ex: browser type)
• perform calculations on user's computer (ex: form validation)

• a web standard (but not supported identically by all browsers)


• NOT related to Java other than by name and some syntactic similarities

Prof. Shital Pashankar


Linking to a JavaScript file: script

<script src="filename" type="text/javascript">


</script> HTML

• script tag should be placed in HTML page's head


• script code is stored in a separate .js file
• JS code can be placed directly in the HTML file's body or head (like CSS)

Prof. Shital Pashankar


Variables
var name = expression; JS

var clientName = "ABC PWR";


var age = 32;
var weight = 127.4; JS

• variables are declared with the var keyword (case sensitive)


• types are not specified, but JS does have types ("loosely typed")
• Number, Boolean, String, Array, Object, Function,
Null, Undefined
• can find out a variable's type by calling typeof

Prof. Shital Pashankar


Number

String Null

Data Types

Boolean Undefined

Object

Function RegExp

Array Date

Prof. Shital Pashankar


Number type
var enrollment = 99;
var Gradepoint = 2.8;
var credits = 5 + 4 + (2 * 3);
JS

• integers and real numbers are the same type (no int vs. double)
• same operators: + - * / % ++ -- = += -= *= /= %=
• similar precedence to Java
• many operators auto-convert types: "2" * 3 is 6

Prof. Shital Pashankar


Boolean type
var flag = true;
var ieIsGood = "IE6" > 0; // false
if ("web devevelopment is great") { /* true */ }
if (0) { /* false */ }
JS

 any value can be used as a Boolean


 "falsey" values: 0, 0.0, NaN, "", null, and undefined

 "truthy" values: anything else

 converting a value into a Boolean explicitly:


 var boolValue = Boolean(otherValue);
 var boolValue = !!(otherValue);

Prof. Shital Pashankar


Special values: null and undefined
var update = null;
var number = 9;
// at this point in the code,
// update is null
// number is 9
// car_speed is undefined
JS

 undefined : has not been declared, does not


exist
 null : exists, but was specifically assigned an
empty or null value

Prof. Shital Pashankar


Math object
var rand1to10 = Math.floor(Math.random() * 10 + 1);
var three = Math.floor(Math.PI);
JS

 methods: abs, ceil, cos, floor, log,


max, min, pow, random, round, sin,
sqrt, tan
 properties: E, PI

Prof. Shital Pashankar


Comments (same as Java)

// single-line comment
/* multi-line comment */
JS

Prof. Shital Pashankar


Logical operators

 > < >= <= && || ! == != === !==


 most logical operators automatically convert
types:
 5 < "7" is true

 42 == 42.0 is true

 "5.0" == 5 is true

 === and !== are strict equality tests; checks both


type and value
 "5.0" === 5 is false

Prof. Shital Pashankar


if/else statement (same as Java)
if (condition) {
statements;
} else if (condition) {
statements;
} else {
statements;
}
JS

 identical structure to Java's if/else statement


 JavaScript allows almost anything as a condition

Prof. Shital Pashankar


for loop (same as Java)

var sum = 0;
for (var i = 0; i < 100; i++) {
sum = sum + i;
} JS

var s1 = "hello";
var s2 = "";
for (var i = 0; i < s1.length; i++) {
s2 += s1.charAt(i) + s1.charAt(i);
}
// s2 stores "hheelllloo" JS

Prof. Shital Pashankar


while loops (same as Java)
while (condition) {
statements;
} JS

do {
statements;
} while (condition);
JS

 break and continue keywords also behave as in


Java

Prof. Shital Pashankar


Popup boxes
alert("message"); // message
confirm("message"); // returns true or false
prompt("message"); // returns user input string
JS

Prof. Shital Pashankar


Arrays
var name = []; // empty array
var name = [value, value, ..., value]; // pre-filled
name[index] = value; // store element
JS

var list = ["Heena", "Deepa", "Leela"];


var st = []; // st.length is 0
st[0] = " Leela "; // st.length is 1
st[1] = “ Meena "; // st.length is 2
st[4] = " Deepa "; // st.length is 5
JS

Prof. Shital Pashankar


Array methods
var a = ["Sagar", "Jason"]; // Sagar, Jason
a.push("Brian"); // Sagar, Jason, Brian
a.unshift("Ketan"); // Ketan, Sagar, Jason, Brian
a.pop(); // Ketan, Sagar, Jason
a.shift(); // Sagar, Jason
a.sort(); // Jason, Sagar
JS

 array serves as many data structures: list, queue, stack, ...


 methods: concat, join, pop, push, reverse, shift,
slice, sort, splice, toString, unshift
 push and pop add / remove from back
 unshift and shift add / remove from front
 shift and pop return the element that is removed

Prof. Shital Pashankar


JavaScript Program To Print Hello World
helloworld.html
<html>
<head>
<script>
// the hello world program
document.write('Hello, World!’);
</script>
</head>
</html>

Prof. Shital Pashankar


JavaScript Program to Add Two Numbers
<script>
var num1 = 5;
var num2 = 3;

// add two numbers


var sum = num1 + num2;

// display the sum


document.write('The sum of ' + num1 + ' and ' + num2 + ' is: ' + sum);
</script>

Prof. Shital Pashankar


Javascript Program to Check if a Number
is Odd or Even
<script>
// take input from the user
number = prompt("Enter a number: ");
if(number % 2 == 0) {
document.write("The number is even.");
}
else {
document.write("The number is odd.");
}
</script>

Prof. Shital Pashankar


JavaScript Program to Find the Square
Root
<script>
// take the input from the user
var number = prompt('Enter the number: ');

var result = Math.sqrt(number);

document.write(`The square root of ${number} is ${result}`);


</script>

Prof. Shital Pashankar


JavaScript Program to Calculate the Area
of a Triangle
<script>
var baseValue = prompt('Enter the base of a triangle: ');
var heightValue = prompt('Enter the height of a triangle: ');

// calculate the area


var areaValue = (baseValue * heightValue) / 2;

document.write("The area of the triangle is "+ areaValue);

</script>

Prof. Shital Pashankar


JavaScript Program for a Simple Calculator
<script>
Var result;
operator = prompt('Enter operator ( either +, -, * or / ): ‘); //
take the operator input
// take the operand input
number1 = parseInt(prompt('Enter first number: '));
number2 = parseInt(prompt('Enter second number: '));
switch(operator) {
case '+': result = number1 + number2;
document.write(number1 + '+’ + number2 + ' = ' + result);
break;
Prof. Shital Pashankar
JavaScript Program for a Simple Calculator
case '-': result = number1 - number2;
document.write(`number1 - number2 = result`); break;
case '*': result = number1 * number2;
document.write(`number1 * number2 = result`); break;
case '/': result = number1 / number2;
document.write(`number1 / number2 = result`); break;
default: document.write('Invalid operator’);
break;
}
</script>

Prof. Shital Pashankar


Write a JavaScript program to calculate the volume of a sphere.(Accept radius from user).

<script>
var r = parseInt(prompt('Enter the radius of a sphere: '));
// calculate the volume
var vol =( (Math.PI *Math.pow(r,3) )*4) / 3;
alert("The volume of the sphere is "+ vol);
</script>

Prof. Shital Pashankar


Write a JavaScript function that reverse a number.
<script>
Function rev(){
num = prompt("Enter a number: ");
arr = num.split("");
arr = arr.reverse();
str = arr.join("");
rev = parseInt(str);
alert(rev);
}
rev();
</script>

Prof. Shital Pashankar


Write a JavaScript program to display the current day and time in the following
format. Sample Output : Today is : Tuesday. Current time is : 10 PM : 30 : 38

<script>
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
d = new Date();
day = days[d.getDay()];
t = d.getHours();
if(t>=11){
t= t-12;
t = t +" PM : "+d.getMinutes()+ " : "+d.getSeconds(); }
else{
t = t +" AM : "+d.getMinutes()+ " : "+d.getSeconds(); }
alert("Today is = "+day+"\n Current time is = "+t);
</script>

Prof. Shital Pashankar


JavaScript functions
function name() {
statement ;
statement ;
...
statement ;
} JS

function myFunction() {
alert("Hello!");
alert("How are you?");
} JS

 the above could be the contents of example.js linked to our


HTML page
 statements placed into functions can be evaluated in
response to user events
Prof. Shital Pashankar
Event-driven programming

Prof. Shital Pashankar


Event-driven programming

 you are used to programs start with a main method (or


implicit main like in PHP)
 JavaScript programs instead wait for user actions called
events and respond to them
 event-driven programming: writing programs driven by user
events

Prof. Shital Pashankar


What is an Event ?
• JavaScript's interaction with HTML is handled through events that occur
when the user or the browser manipulates a page.
• When the page loads, it is called an event. When the user clicks a button,
that click too is an event. Other examples include events like pressing any
key, closing a window, resizing a window, etc.
• Developers can use these events to execute JavaScript coded responses,
which cause buttons to close windows, messages to be displayed to users,
data to be validated, and virtually any other type of response imaginable.
• Events are a part of the Document Object Model (DOM) Level 3 and every
HTML element contains a set of events which can trigger JavaScript Code.

Prof. Shital Pashankar


Event handlers
<element attributes onclick="function();">...
HTML

<button onclick="myFunction();">Click me!</button>


HTML

• JavaScript functions can be set as event handlers


• when you interact with the element, the function will execute
• onclick is just one of many event HTML attributes we'll use
• but popping up an alert window is disruptive and annoying
• A better user experience would be to have the message appear on the
page...

Prof. Shital Pashankar


JavaScript HTML DOM Events Examples
Input Events

Prof. Shital Pashankar


JavaScript HTML DOM Events Examples
Input Events

Prof. Shital Pashankar


JavaScript HTML DOM Events Examples
Click Events

Load Events

Prof. Shital Pashankar


JavaScript HTML DOM Events Examples

Mouse Events

Prof. Shital Pashankar


Buttons
<button>Click me!</button> HTML

• button's text appears inside tag; can also contain


images
• To make a responsive button or other UI control:
1. choose the control (e.g. button) and event (e.g.
mouse 1. click) of interest
2. write a JavaScript function to run when the
event occurs
3. attach the function to the event on the control

Prof. Shital Pashankar


• most JS code manipulates
elements on an HTML page
• we can examine elements'
state
• e.g. see whether a box is checked

• we can change state


• e.g. insert some new text into a
div

• we can change styles


• e.g. make a paragraph red

Prof. Shital Pashankar


Prof. Shital Pashankar
var name = document.getElementById("value");
JS SYNTAX

<button onclick="changeText();">Click me!</button>


<span id="output">replace me</span>
<input id="textbox" type="text" /> HTML

function changeText() {
var span = document.getElementById("output");
var textBox = document.getElementById("textbox");

textbox.style.color = "red";

} JS

Prof. Shital Pashankar


 document.getElementById returns the DOM object for an
element with a given id
 can change the text inside most elements by setting the
innerHTML property
 can change the text in form controls by setting the value
property

Prof. Shital Pashankar


Attribute Property or style object
color color
padding padding
background-color backgroundColor
border-top-width borderTopWidth
Font size fontSize
Font famiy fontFamily
Prof. Shital Pashankar
Preetify
function changeText() {
//grab or initialize text here

// font styles added by JS:


text.style.fontSize = "13pt";
text.style.fontFamily = "Comic Sans MS";
text.style.color = "red"; // or pink?
} JS

Prof. Shital Pashankar


Examples:

<!DOCTYPE html>
<html>
<body>
<button onclick= "getElementById('demo').innerHTML=Date()"> The time
is?</button>
<p id="demo">Result will appear here….</p>
</body>
</html>

Prof. Shital Pashankar


Example: onchange event
<html><head><script>
function myFunction() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script></head><body>
Enter your name: <input type="text" id="fname" onkeyup="myFunction()">
<p>When you type in the input field, a function is triggered which transforms
the input text to upper case.</p>
</body></html>
Prof. Shital Pashankar
Example: onkeypress event
<html><head><script>
function myFunction() {
alert("You pressed a key inside the input field");
}
</script></head><body>

<p>A function is triggered when the user is pressing a key in the input field.</p>
<input type="text" onkeypress="myFunction()">

</body></html>

Prof. Shital Pashankar


Javascript Object

Objects in Javascript are divided into three categories.


1. Built-in objects
2. Browser Objects
3. User-defined objects.

Prof. Shital Pashankar


1. Built-in Objects
• Array, string, math, Date are commonly used built-in
objects.
• Array: Using Keyword new, you can create an
instance of the object.
For ex. Var myarray=new array();
• String: String object is used to manipulate a stored
piece of text.
var text =”PHP and Javascript” ;
Document.write(text.length);

Prof. Shital Pashankar


String type
var s = "Connie Client";
var fName = s.substring(0, s.indexOf(" ")); // "Connie"
var len = s.length; // 13
var s2 = 'Melvin Merchant';
JS

• methods: charAt, charCodeAt, fromCharCode, indexOf,


lastIndexOf, replace, split, substring,
toLowerCase, toUpperCase
• charAt returns a one-letter String (there is no char type)

• length property (not a method as in Java)


• Strings can be specified with "" or ''
• concatenation with + : 1 + 1 is 2, but "1" + 1 is "11"

Prof. Shital Pashankar


More about String
 escape sequences behave as in Java: \' \" \& \n \t \\
 converting between numbers and Strings:
var count = 10;
var s1 = "" + count; // "10"
var s2 = count + " bananas, ah ah ah!"; // "10 bananas, ah
ah ah!"
var n1 = parseInt("42 is the answer"); // 42
var n2 = parseFloat("booyah"); // NaN JS

• accessing the letters of a String:


var firstLetter = s[0]; // fails in IE
var firstLetter = s.charAt(0); // does work in IE
var lastLetter = s.charAt(s.length - 1); JS

Prof. Shital Pashankar


Splitting strings: split and join
var s = "the quick brown fox";
var a = s.split(" "); // ["the", "quick", "brown", "fox"]
a.reverse(); // ["fox", "brown", "quick", "the"]
s = a.join("!"); // "fox!brown!quick!the"
JS

 split breaks apart a string into an array using a delimiter


 can also be used with regular expressions (seen later)
 join merges an array into a single string, placing a delimiter
between them

Prof. Shital Pashankar


JavaScript Program to Sort Words in
Alphabetical Order
<script>
string1 = prompt('Enter a sentence: '); // take input
words = string1.split(' '); // converting to an array
words.sort(); // sort the array elements
document.write('The sorted words are:'); // display the sorted words
for (element of words) {
document.write(element,"<br>");
} </script>
//The for...of statement creates a loop iterating over iterable objects, including: built-
in String, Array, array-like objects
Prof. Shital Pashankar
Creating Date Objects
new Date()
new Date(year, month, day, hours, minutes, seconds,
milliseconds)
new Date(milliseconds)
new Date(date string)
• new Date() creates a new date object with the current date and
time
• new Date(year, month, ...) creates a new date object with
a specified date and time. 7 numbers specify year, month,
day, hour, minute, second, and millisecond (in that order)

• new Date(milliseconds) creates a new date object as zero time plus milliseconds

• new Date(dateString) creates a new date object from a date string

Prof. Shital Pashankar


Example
<!DOCTYPE html>
<html><body><p id="demo"></p>

<script>
var time = new Date().getHours();
if (time < 10) {
document.write("Good morning ");
} else if (time < 20) {
document.write("Good day");
} else {
document.write("Good evening");
}
</script></body></html>

Prof. Shital Pashankar


2.Browser Objects
• Browser Object Model (BOM) is a collection of objects that interact with
the browser window.
• These objects include the Window object, history object, location object,
navigator object, screen object and document object.
• The window object method is the top object in BOM hierarchy.
• he window object is used to move, resize windows , create a new
windows.
• Window object is also used to create dialogue boxes such as alert boxes.
• Some commonly used methods of window object are open, close,
confirm, alert, prompt etc.

Prof. Shital Pashankar


Window

History Navigator Screen Document Location

Prof. Shital Pashankar


The Window Object
• The window object is supported by all browsers. It represents the
browser's window
• All global JavaScript objects, functions, and variables automatically
become members of the window object.
• Global variables are properties of the window object.
• Global functions are methods of the window object.
• Even the document object (of the HTML DOM) is a property of the
window object:
window.document.getElementById("header");
• is the same as:
document.getElementById("header");

Prof. Shital Pashankar


Window Size
• Two properties can be used to determine the size of the browser window.
• Both properties return the sizes in pixels:
• window.innerHeight - the inner height of the browser window (in pixels)
• window.innerWidth - the inner width of the browser window (in pixels)

• Some other methods:


• window.open() - open a new window
• window.close() - close the current window
• window.moveTo() - move the current window
• window.resizeTo() - resize the current window

Prof. Shital Pashankar


Window Screen

• The window.screen object contains information about the user's screen.


• The window.screen object can be written without the window prefix.
• Properties:
1. screen.width
2. screen.height
3. screen.availWidth
4. screen.availHeight
5. screen.colorDepth
6. screen.pixelDepth

Prof. Shital Pashankar


Window Location
• The window.location object can be used to get the current page address (URL) and
to redirect the browser to a new page.
• The window.location object can be written without the window prefix.
• Some examples:
1. window.location.href returns the href (URL) of the current page
2. window.location.hostname returns the domain name of the web host
3. window.location.pathname returns the path and filename of the current page
4. window.location.protocol returns the web protocol used (http: or https:)
5. window.location.assign() loads a new document

Prof. Shital Pashankar


Window History

• The window.history object contains the browsers history.


• The window.history object can be written without the window prefix.
• To protect the privacy of the users, there are limitations to how JavaScript can
access this object.
• Some methods:
1. history.back() - same as clicking back in the browser
2. history.forward() - same as clicking forward in the browser

Prof. Shital Pashankar


Window Navigator

• The window.navigator object contains information about the visitor's browser.


• The window.navigator object can be written without the window prefix.
• Navigator.cookieEnabled property returns true if cookies are enabled, otherwise
false
• Navigator.language property returns the browser's language
• Navigator.platform property returns the browser platform (operating system)
• navigator.javaEnabled() method returns true if Java is enabled

Prof. Shital Pashankar


3. User-defined objects.

• With JavaScript, you can define and create your own objects.

• There are different ways to create new objects:

1. Define and create a single object, using an object literal.


2. Define and create a single object, with the keyword new.
3. Define an object constructor, and then create objects of the
constructed type.

Prof. Shital Pashankar


Using an Object Literal

• This is the easiest way to create a JavaScript Object.


• Using an object literal, you both define and create an object in one
statement.
• An object literal is a list of name: value pairs (like age:50) inside curly
braces {}.
• The following example creates a new JavaScript object with four
properties:

Prof. Shital Pashankar


Using an Object Literal
<!DOCTYPE html>
<html> <body> <p>Creating a JavaScript Object.</p>
<p id="demo"></p>
<script>
var person = {
firstName : "John",
lastName : "Doe",
age : 50,
eyeColor : "blue" };
document.getElementById("demo").innerHTML = person.firstName + " is " +
person.age + " years old."; </script> </body> </html>

Prof. Shital Pashankar


Using the JavaScript Keyword new
<!DOCTYPE html>
<html>
<body><p id="demo"></p>
<script>
var person = new Object();
person.firstName = "Indira";
person.lastName = "College";
person.age = 50;
person.eyeColor = "blue";
document.getElementById("demo").innerHTML = person.firstName + " is " +
person.age + " years old.";
</script></body></html>

Prof. Shital Pashankar


Using object constructor
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
var myFather = new Person("ABC", "DEF", 50, "blue");
var myMother = new Person("STR", "RST", 48, "green");

The this Keyword


• In JavaScript, the thing called this is the object that "owns" the code.
• The value of this, when used in an object, is the object itself.
• In a constructor function this does not have a value. It is a substitute
for the new object. The value of this will become the new object when
a new object is created.

Prof. Shital Pashankar


JQUERY

Prof. Shital Pashankar


What is jQuery?

• jQuery is a fast and concise JavaScript Library created by John Resig


in 2006 with a nice motto: Write less, do more.
• jQuery simplifies HTML document traversing, event handling,
animating, and Ajax interactions for rapid web development.
• jQuery is a JavaScript toolkit designed to simplify various tasks by
writing less code.

Prof. Shital Pashankar


jQuery Features:
1. DOM manipulation − The jQuery made it easy to select DOM
elements, negotiate them and modifying their content by using
cross-browser open source selector engine called Sizzle.
2. Event handling − The jQuery offers an elegant way to capture a
wide variety of events, such as a user clicking on a link, without the
need to clutter the HTML code itself with event handlers.
3. AJAX Support − The jQuery helps you a lot to develop a responsive
and feature-rich site using AJAX technology.

Prof. Shital Pashankar


jQuery Features:
4. Animations − The jQuery comes with plenty of built-in animation
effects which you can use in your websites.
5. Lightweight − The jQuery is very lightweight library - about 19KB in
size (Minified and gzipped).
6. Cross Browser Support − The jQuery has cross-browser support,
and works well in IE 6.0+, FF 2.0+, Safari 3.0+, Chrome and Opera
9.0+
7. Latest Technology − The jQuery supports CSS3 selectors and
basic XPath syntax.

Prof. Shital Pashankar


How to use jQuery?
• There are two ways to use jQuery.
• Local Installation − You can download jQuery library on your local machine
and include it in your HTML code.
• Go to the https://jquery.com/download/ to download the latest version available.
• Now put downloaded jquery-2.1.3.min.js file in a directory of your website, e.g.
/jquery.

• CDN Based Version − You can include jQuery library into your HTML code
directly from Content Delivery Network (CDN).
• You can include jQuery library into your HTML code directly from Content Delivery
Network (CDN). Google and Microsoft provides content deliver for the latest
version.
• We are using Google CDN version of the library throughout this chapter.

Prof. Shital Pashankar


jQuery Syntax
• The jQuery syntax is tailor-made for selecting HTML elements
and performing some action on the element(s).
• Basic syntax is: $(selector).action()

• A $ sign to define/access jQuery


• A (selector) to "query (or find)" HTML elements
• A jQuery action() to be performed on the element(s)

Prof. Shital Pashankar


jQuery Selectors
• 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: $().

Prof. Shital Pashankar


1. 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:
• $(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});

Prof. Shital Pashankar


2. 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:
$(document).ready(function(){
$("button").click(function(){
$("#test").hide();
});
});

Prof. Shital Pashankar


3. The .class Selector
• The jQuery .class selector finds elements with a specific class.

• To find elements with a specific class, write a period character, followed by the
name of the class:
$(document).ready(function(){
$("button").click(function(){
$(".test").hide();
});
});

Prof. Shital Pashankar


Examples of jQuery Selectors
Syntax Description
$("*") Selects all elements

$(this) Selects the current HTML element

$("p.intro") Selects all <p> elements with class="intro"

$("p:first") Selects the first <p> element

$("ul li:first") Selects the first <li> element of the first <ul>

$("ul li:first-child") Selects the first <li> element of every <ul>


Prof. Shital Pashankar
Examples of jQuery Selectors
Syntax Description

$("[href]") Selects all elements with an href attribute


$("a[target='_blank']") Selects all <a> elements with a target attribute value equal
to "_blank"
$("a[target!='_blank']") Selects all <a> elements with a target attribute value NOT
equal to "_blank"

$(":button") Selects all <button> elements and <input> elements of


type="button"
$("tr:even") Selects all even <tr> elements
$("tr:odd") Selects all odd <tr> elements
Prof. Shital Pashankar
<html>
<head><title>The jQuery Example</title>
<script type = "text/javascript" src =
"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script>

<script type = "text/javascript">


$(document).ready(function() {
document.write("Hello, World!");
});
</script></head>
<body>
<h1>Hello</h1>
</body></html>

Prof. Shital Pashankar


jQuery - DOM Manipulation
• JQuery provides methods to manipulate DOM in efficient way. You do not
need to write big code to modify the value of any element's attribute or to
extract HTML code from a paragraph or division.
• JQuery provides methods such as .attr(), .html(), and .val() which act as
getters, retrieving information from DOM elements for later use.

Prof. Shital Pashankar


Content Manipulation
• The html( ) method gets the html contents (innerHTML) of the first matched
element.
• Here is the syntax for the method −
• selector.html( )

<html><head><title>The jQuery Example</title>


<script type = "text/javascript" src =
"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("div").click(function () {
var content = $(this).html();
$("#result").text( content );

Prof. Shital Pashankar


});
}); </script>
<style>
#division{ margin:10px;padding:12px; border:2px solid #666; width:60px;}
</style>
</head>

<body>
<p>Click on the square below:</p>
<span id = "result"> </span>
<div id = "division" style = "background-color:blue;">
This is Blue Square!!
</div>
</body>
</html>

Prof. Shital Pashankar


DOM Element Replacement
• You can replace a complete DOM element with the
specified HTML or DOM elements. The replaceWith(
content ) method serves this purpose very well.
• Here is the syntax for the method −
• selector.replaceWith( content )
• Here content is what you want to have instead of original element.
This could be HTML or simple text.

Prof. Shital Pashankar


Removing DOM Elements
• There may be a situation when you would like to remove one or more
DOM elements from the document. JQuery provides two methods to
handle the situation.
• The empty( ) method remove all child nodes from the set of matched
elements where as the method remove( expr ) method removes all
matched elements from the DOM.
• Here is the syntax for the method −
• selector.remove( [ expr ]) or selector.empty( )

Prof. Shital Pashankar


Inserting DOM Elements
• There may be a situation when you would like to insert new one or
more DOM elements in your existing document. JQuery provides
various methods to insert elements at various locations.
• The after( content ) method insert content after each of the matched
elements where as the method before( content ) method inserts
content before each of the matched elements.
• Here is the syntax for the method −
• selector.after( content ) or selector.before( content )

Prof. Shital Pashankar


DOM Manipulation Methods
Sr. Method & Description
No.
1 after( content ) Insert content after each of the matched elements.
2 append( content ) Append content to the inside of every matched element.
3 appendTo( selector ) Append all of the matched elements to another, specified, set of elements.
4 before( content ) Insert content before each of the matched elements.
5 clone( bool ) Clone matched DOM Elements, and all their event handlers, and select the clones.
6 clone( ) Clone matched DOM Elements and select the clones.
7 empty( ) Remove all child nodes from the set of matched elements.
8 html( val ) Set the html contents of every matched element.
9 html( ) Get the html contents (innerHTML) of the first matched element.
10 insertAfter( selector ) Insert all of the matched elements after another, specified, set of elements.
11 insertBefore( selector ) Insert all of the matched elements before another, specified, set of elements.
12 prepend( content ) Prepend content to the inside of every matched element.
Prof. Shital Pashankar
DOM Manipulation Methods
Sr. Method & Description
No.
13 prependTo( selector ) Prepend all of the matched elements to another, specified, set of elements.
14 remove( expr ) Removes all matched elements from the DOM.
15 replaceAll( selector ) Replaces the elements matched by the specified selector with the matched elements.
16 replaceWith( content ) Replaces all matched elements with the specified HTML or DOM elements.
17 text( val ) Set the text contents of all matched elements.
18 text( ) Get the combined text contents of all matched elements.
19 wrap( elem ) Wrap each matched element with the specified element.
20 wrap( html ) Wrap each matched element with the specified HTML content.
21 wrapAll( elem ) Wrap all the elements in the matched set into a single wrapper element.
22 wrapAll( html ) Wrap all the elements in the matched set into a single wrapper element.
23 wrapInner( elem ) Wrap the inner child contents of each matched element (including text nodes) with a DOM element.
24 wrapInner( html ) Wrap the inner child contents of each matched element (including text nodes) with an HTML structure.
Prof. Shital Pashankar
Write a JQuery code that is able to hide a current paragraph when the
button is clicked Question

<!DOCTYPE
html><html><head><script src="https://ajax.googleapis.com/ajax/
libs/jquery/3.7.1/jquery.min.js"></script><script>
$(document).ready(function(){
$("#hide").click(function(){
$("p").hide(); });
});
</script></head><body><p>If you click on the "Hide" button,
I will disappear.</p>
<button id="hide">Hide</button>
</body></html>

Prof. Shital Pashankar


Write a suitable JQuery code that is able to display a button that can hide and
show a paragraph with a specific ID (hint: can use hide and show)

<!DOCTYPE html><html><head><script
src="jquery.min.js"></script><script>
$(document).ready(function(){
$("#hide").click(function(){
$("#p1").hide(); });
$("#show").click(function(){
$("#p1").show(); });
});
</script></head><body><p id="p1">If you click on the "Hide"
button, I will disappear.</p>
<button id="hide">Hide</button>
<button id="show">Show</button></body></html>

Prof. Shital Pashankar


Write a suitable JQuery code that is able to display a button that can hide and show
a paragraph with a specific ID (hint: can use hide and show with 1000 as the
parameter)
<!DOCTYPE html><html><head><script
src="jquery.min.js"></script><script>
$(document).ready(function(){
$("#hide").click(function(){
$("#p1").hide(1000); });
$("#show").click(function(){
$("#p1").show(1000); });
});
</script></head><body><p id="p1">If you click on the "Hide"
button, I will disappear.</p>
<button id="hide">Hide</button>
<button id="show">Show</button></body></html>
Prof. Shital Pashankar
Write a suitable JQuery code that is able to display a button that can hide and
show a paragraph with a specific ID (hint: can use toggle)
<!DOCTYPE html><html><head><script src="jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#1").toggle();
});
});</script></head><body>
<button>Toggle between hiding and showing the
paragraphs</button>
<p id = "1">This is a paragraph with little content.</p>
<p id = "2">This is another small paragraph.</p></body></html>

Prof. Shital Pashankar


Write a suitable JQuery code when the cursor hover a certain word with
a specific ID, a new <p> element will be displayed saying "Hi there". When
the cursor is away, the <p> element will display "Bye".

<!DOCTYPE html><html><head><title>Hover Example</title>


<script src="jquery.min.js"></script> <script>
$(document).ready(function() {
$('#trigger').hover(function(){
$('#message').text('<p>Hi there</p>').show();
}, function(){
$('#message').text('<p>Bye</p>').show();
});
});
</script></head>
<body><p id="trigger">Hover over me!</p>
<p id="message">ok</p></body></html>
Prof. Shital Pashankar
first moves the <div> element to the right, and then increases the font size of
the text

<!DOCTYPE html><html><head><script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js
"></script><script>
$(document).ready(function(){
$("button").click(function(){
var div = $("div");
div.animate({left: '100px'}, "slow");
div.animate({fontSize: '3em'},
"slow"); });});</script> </head><body>
<button>Start Animation</button>
<p>By default, all HTML elements have a static position, and cannot
be moved. To manipulate the position, remember to first set the CSS
position property of the element to relative, fixed, or absolute!</p>
<div
style="background:#98bf21;height:100px;width:200px;position:absolute;
"> HELLO </div></body></html>

Prof. Shital Pashankar


first change the color to red of <p> element and then slowly slide-up and
slide-down the text.
<!DOCTYPE html><html><head><script src="jquery.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 is fun!!</p>
<button>Click me</button></body></html>

Prof. Shital Pashankar


how to get the value of an input field with the jQuery

<!DOCTYPE html><html><head><script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
alert("Value: " + $("#test").val());
});
});
</script></head><body>
<p>Name: <input type="text" id="test" value="Mickey Mouse"></p>
<button>Show Value</button></body></html>

Prof. Shital Pashankar

You might also like