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

J Query Tutorial

Uploaded by

vinothchintam12
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

J Query Tutorial

Uploaded by

vinothchintam12
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 76

JQuery

jQuery is
a fast, lightweight, and feature-rich JavaScript library that is based on the principle "write less, do more".

It's easy-to-use APIs makes the things like HTML document traversal and manipulation, event handling, adding animation effects
to a web page much simpler that works seamlessly across all the major browsers like Chrome, Firefox, Safari, Internet Explorer, etc.

Open-source JavaScript library that simplifies the interactions between an HTML/CSS document, or more precisely the
Document Object Model (DOM), and JavaScript.

jQuery also gives you the ability to create an Ajax based application in a quick and simple way

jQuery was originally created by John Resig in early 2006. The jQuery project is currently run and maintained by a distributed
group of developers as an open-source project.

What You Can Do with jQuery

There are lot more things you can do with jQuery.

• You can easily select elements to perform manipulation.

• You can easily create effect like show or hide elements, sliding transition, and so on.

• You can easily create complex CSS animation with fewer lines of code.

• You can easily manipulate DOM elements and their attributes.

• You can easily implement Ajax to enable asynchronous data exchange between client and server.

• You can easily traverse all around the DOM tree to locate any element.

• You can easily perform multiple actions on an element with a single line of code.

• You can easily get or set dimensions of the HTML elements.

Advantages of Using jQuery

1. Save lots of time


2. Simplify common JavaScript tasks
3. Easy to use
4. Compatible with browsers
5. Absolutely Free

Downloading jQuery

To get started, first download a copy of jQuery and include it in your document.

There are two versions of jQuery available for downloading

— compressed and uncompressed.

You can download jQuery from here: https://jquery.com/download/

Once you've downloaded the jQuery file you can see it has .js extension, because the jQuery is just a JavaScript library, therefore you can
include the jQuery file in your HTML document with the <script> element just like you include normal JavaScript files.

Linking JQuery

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Simple HTML Document</title>


<link rel="stylesheet" href="css/style.css">

<script src="js/jquery-3.5.1.min.js"></script>

</head>

<body>

<h1>Hello, World!</h1>

</body>

</html>

Why to use jQuery?

Some of the key points that support the answer for why to use jQuery:

1. It helps us to manipulate HTML and CSS


2. It helps us to manipulate DOM (Document Object Model) elements
3. Provides event methods to trigger and respond to an events on a html page such as mouse click,
keypress etc.
4. Implements AJAX calls.

Advantages:
• Wide range of plug-ins that allows developers to create plug-ins on top of the JavaScript library.
• Large development community.
• It is a lot easier to use compared to standard javascript and other javascript libraries.
• It lets users develop Ajax templates with ease. Ajax enables a sleeker interface where actions can be
performed on pages without requiring the entire page to be reloaded.
• Being Light weight and a powerful chaining capabilities makes it more strong.

jQuery is widely famous with its philosophy of “Write less, do more.” This philosophy can be further
elaborated as three concepts:

• Finding some elements (via CSS selectors) and doing something with them (via jQuery methods) i.e.
locate a set of elements in the DOM, and then do something with that set of elements.
• Chaining multiple jQuery methods on a set of elements
• Using the jQuery wrapper and implicit iteration

Using jQuery (JS) library on HTML page


There are several ways to start using jQuery on your web site.

1.Use the Google-hosted/ Microsoft-hosted content delivery network (CDN) to include a version of jQuery.
2.Download own version of jQuery from jQuery.com and host it on own server or local filesystem

jQuery's CDN provided by StackPath


<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
You can also include jQuery through Google and Microsoft CDN's.

Basic syntax for any jQuery function is:

$(selector).action()
A $ sign is to define/access jQuery
A (selector) is to “query (or find)” HTML elements in html page
A jQuery action() is the action to be performed on the selected element(s)
Creating Your First jQuery Powered Web Page
So far you have understood the purposes of jQuery library as well as how to include this in your document, now
it's time to put jQuery into real use.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My First jQuery Powered Web Page</title>
<link rel="stylesheet" href="css/style.css">
<script src="js/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("h1").css("color", "#0088ff");
});
</script>
</head>
<body>
<h1>Hello, World!</h1>
</body>
</html>

Example 2:
<!DOCTYPE html>
<html>
<head>
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<script>
$(document).ready(function ()
{
$("h2").click(function ()
{
$(this).hover();
});
});
</script>
</head>
<body>
<center>
<h2 style="color: green;">
Elysium Academy
</h2>
</center>
</body>
</html>
jQuery | Syntax

Syntax:

$(selector).action()

$ sign: It grants access to jQuery.


(selector): It is used to find HTML elements.
jQuery action(): It is used to perform actions on the elements.

Used to hide the current element.


$(this).hide()
Used to hide all <p> elements.
$(“p”).hide()
Used to hide all elements with class=”test”.
$(“.test”).hide()
Used to hide the element with id=”test”.
$(“#test”).hide()

Document Ready Event:


$( document ).ready()
jQuery Methods are inside a Document ready event for easy reading of code.

A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you.
Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready
for JavaScript code to execute.

$(document).ready(function()
{
// jQuery Method
});

This is to check and stop the jquery before the document is finished loading. This method also allows you to have
JavaScript code before the body of your document, in the head section.

Some actions that can fail if the method is run before the loaded document:
Get the image size which is not loaded or hide element which is not created yet.

The shorter method for document ready:

$(function(){

// jQuery Method

});

jQuery selectors
jQuery selectors are used to select the HTML element(s) and allows you to manipulate the HTML element(s) in a
way we want.
It selects the HTML elements on a variable parameter such as their name, classes, id, types, attributes, attribute
values, etc. All selectors in jQuery are selected using a special sign i.e. dollar sign and parentheses:

$("selector-name")

Elements Selector :
The elements selector selects the element on the basis of its name.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
</head>
<body>
<h1>Welcome to Elysium Academy </h1>
<h2>This is Web Technology section </h2>
<br/>
<button>Hide</button>
<script type="text/javascript">
$("button").click(function() {
$("h1").hide();
});
</script>
</body>
</html>

Id Selector :
The id selector selects the element on the basis of its id.
Example:-
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
</head>
<body>
<p id="xyz"> Welcome to Elysium Academy</p>
<p id="XYZ">Computer Science Portal </p>
<br/>
<button>Hide</button>
<script type="text/javascript">
$("button").dblclick(function() {
$("#xyz").hide();
});
</script>
</body>
</html>

Class Selector :
The class selector selects the element on the basis of its class.
Example :
In this example, when the user clicks on button, the element with class = “GFG” gets hidden.
Code :-

<!DOCTYPE html>
<html>

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
</head>
<body>
<p class="abc">Welcome to All</p>
<p class="ABC">Explore More about EAP Ltd </p>
<br/>
<button>Hide</button>
<script type="text/javascript">
$("button").click(function() {
$(".ABC").hide();
});
</script>
</body>
</html>

jQuery Event methods:


Event refers to the actions performed by the site visitor during their interactivity with the website (or webpage).
There can be various types of events such as
➢ User clicks on the button.
➢ User moves mouse pointer over an image.
➢ User pressed any key from keyboard, etc.

click(),dblclick(),mouseenter(),mouseleave(),mousedown(),mouseup(),hover()

Get and Set Methods:

jQuery has various methods to get the value of an attribute and set the attribute to specific value.There
methods are powerful enough to the change the website content and its style. Some of them are:

text() – This method is used get or set the text content of selected HTML element.

html() – This method is used get or set the content of selected elements (including HTML elements).

val() – This method is used get or set the value of various form fields in the webpage.

attr() – This method is used get or set the value of various attributes in the webpage.

css() – This method is used get or set the value of various CSS properties in the webpage.

<!DOCTYPE html>

<html>

<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">

</script>

<style type="text/css">

#e5 {

width: 100px;

height: 100px;

border-radius: 0px;

background-color: aqua;

</style>

</head>

<body>

<p id="e1">Welcome.</p>

<p id="e2">Learn and Explore</p>


<p>

<input type="text" id="e3" value="jQuery is powerful!" />

</p>

<p id="e4" align="left">Geeks for Geeks</p>

<p>

<div id="e5"></div>

</p>

<button id="gfg1">Change Text</button>

<button id="gfg2">Change HTML</button>

<button id="gfg3">Change Value</button>

<button id="gfg4">Change Alignment</button>

<button id="gfg5">Change Shape</button>

<script type="text/javascript">

$("#gfg1").click(function() {

$("#e1").text("Geeks for Geeks");

});

$("#gfg2").click(function() {

$("#e2").html("<b>Enrich your Knowledge.</b>");

});

$("#gfg3").click(function() {

$("#e3").val("jQuery at Geeks for Geeks");

});

$("#gfg4").click(function() {

$("#e4").attr("align", "center");

});

$("#gfg5").click(function() {

$("#e5").css("border-radius", "50px");

});

</script>

</body>

</html>
JQuery Manuplation

How to get or set the element's content and attribute value as well as the from control value using jQuery.

jQuery Get or Set Contents and Values

Some jQuery methods can be used to either assign or read some value on a selection. A few of these
methods are text(), html(), attr(), and val().

When these methods are called with no argument, it is referred to as a getters, because it gets (or reads) the
value of the element.

When these methods are called with a value as an argument, it's referred to as a setter because it sets (or
assigns) that value.

jQuery text() Method

The jQuery text() method is either used to get the combined text contents of the selected elements,
including their descendants, or set the text contents of the selected elements.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>jQuery Get Text Contents of the Elements</title>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>

$(document).ready(function(){

$(".btn-one").click(function(){

var str = $("p").text();

alert(str);

});

$(".btn-two").click(function(){

var str = $("p:first").text();

alert(str);

});

$(".btn-three").click(function(){

var str = $("p.extra").text();

alert(str);

});

});

</script>

</head>

<body>
<button type="button" class="btn-one">Get All Paragraph's Text</button>

<button type="button" class="btn-two">Get First Paragraph's Text</button>

<button type="button" class="btn-three">Get Last Paragraph's Text</button>

<p>This is a paragraph.</p>

<p>This is another paragraph.</p>

<p class="extra">This is one more paragraph.</p>

</body>

</html>

JQuery with setter method to manuplate the value of the elements

Example:-

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>jQuery Set Text Contents of the Elements</title>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>

$(document).ready(function(){

$(".btn-one").click(function(){

$("p").text("This is demo text.");

});

$(".btn-two").click(function(){

$("p:first").text("This is another demo text.");

});

$(".btn-three").click(function(){

$("p.empty").text("This is one more demo text.");

});

});

</script>

</head>

<body>

<button type="button" class="btn-one">Set All Paragraph's Text</button>

<button type="button" class="btn-two">Set First Paragraph's Text</button>

<button type="button" class="btn-three">Set Empty Paragraph's Text</button>


<p>This is a test paragraph.</p>

<p>This is another test paragraph.</p>

<p class="empty"></p>

</body>

</html>

jQuery html() Method

The jQuery html() method is used to get or set the HTML contents of the elements.

Example

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>jQuery Get HTML Contents of an Element</title>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>

$(document).ready(function(){

$(".btn-one").click(function(){

var str = $("p").html();

alert(str);

});

$(".btn-two").click(function(){

var str = $("#container").html();

alert(str);

});

});

</script>

</head>

<body>

<button type="button" class="btn-one">Get Paragraph's HTML Contents</button>

<button type="button" class="btn-two">Get Container's HTML Contents</button>

<div id="container">

<h1>Hello World!</h1>

<p>The quick <b>brown fox</b> jumps over the lazy dog.</p>

</div>
</body>

</html>

Set HTML Contents with html() Method

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>jQuery Set HTML Contents of the Element</title>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>

$(document).ready(function(){

$("button").click(function(){

$("body").html("<p>Hello World!</p>");

});

});

</script>

</head>

<body>

<button type="button">Write Message</button>

</body>

</html>

jQuery attr() Method

You can use the jQuery attr() method to either get the value of an element's attribute or set one or more
attributes for the selected element.

Get Attribute Value with attr() Method

The following example will show you how get the href attribute of the hyperlink i.e. the <a> element as well
as the alt attribute of an <img> element:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>jQuery Get an Element's Attribute Value</title>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>
$(document).ready(function(){

$(".btn-one").click(function(){

var str = $("a").attr("href");

alert(str);

});

$(".btn-two").click(function(){

var str = $("img#sky").attr("alt");

alert(str);

});

});

</script>

</head>

<body>

<button type="button" class="btn-one">Get Link's HREF Attribute</button>

<button type="button" class="btn-two">Get Image ALT Attribute</button>

<p><a href="https://www.abc.com/">Abc&co</a></p>

<img id="sky" src="/examples/images/sky.jpg" alt="Cloudy Sky">

</body>

</html>

Set Attributes with attr() Method

The following example will show you how to set the checked attribute of the checkbox.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>jQuery Set Element's Attribute Value</title>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>

$(document).ready(function(){

$("button").click(function(){

$('input[type="checkbox"]').attr("checked", "checked");

});

});

</script>
</head>

<body>

<p><label><input type="checkbox"></label> I agree with terms and conditions.</p>

<button type="button">Check</button>

</body>

</html>

The attr() method also allows you to set multiple attributes at a time. The following example will show you
how to set the class and title attribute for the <img> elements.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>jQuery Set Multiple Attribute for the Elements</title>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>

$(document).ready(function(){

$("button").click(function(){

$("img").attr({

"class" : "frame",

"title" : "Hot Air Balloons"

});

});

});

</script>

<style>

.frame{

border: 6px solid #000;

</style>

</head>

<body>

<button type="button">Set Attributes for Image</button>

<p>

<img src="/examples/images/balloons.jpg" alt="Hot Air Balloons">


</p>

</body>

</html>

jQuery Insert New Content

jQuery provides several methods, like append(), prepend(), html(), text(), before(), after(), wrap() etc. that
allows us to insert new content inside an existing element.

The jQuery html() and text() methods have already covered in the previous chapter, so in this chapter, we
will discuss about the rest of them.

jQuery append() Method

The jQuery append() method is used to insert content to the end of the selected elements.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Inserting HTML Contents At the End of the Elements in jQuery</title>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>

$(document).ready(function(){

// Append all paragraphs on document ready

$("p").append(' <a href="#">read more...</a>');

// Append a div container on button click

$("button").click(function(){

$("#container").append("This is demo text.");

});

});

</script>

</head>

<body>

<button type="button">Insert Text</button>

<div id="container">

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam eu sem tempor, varius quam at, luctus
dui. Mauris magna metus, dapibus nec turpis vel, semper malesuada ante.</p>

<p>Quis quam ut magna consequat faucibus. Pellentesque eget nisi a mi suscipit tincidunt. Ut tempus
dictum risus. Pellentesque viverra sagittis quam at mattis. Suspendisse potenti.</p>
</div>

</body>

</html>

jQuery prepend() Method

The prepend() method is used to insert content to the beginning of the selected elements.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Inserting HTML Contents At the Start of the Elements in jQuery</title>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>

$(document).ready(function(){

// Prepend all paragraphs on document ready

$("p").prepend("<strong>Note:</strong> ");

// Prepend a div container on button click

$("button").click(function(){

$("#container").prepend("This is demo text.");

});

});

</script>

</head>

<body>

<button type="button">Insert Text</button>

<div id="container">

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam eu sem tempor, varius quam at, luctus
dui. Mauris magna metus, dapibus nec turpis vel, semper malesuada ante.</p>

<p>Quis quam ut magna consequat faucibus. Pellentesque eget nisi a mi suscipit tincidunt. Ut tempus
dictum risus. Pellentesque viverra sagittis quam at mattis. Suspendisse potenti.</p>

</div>

</body>

</html>
Insert Multiple Elements with append() & prepend() Method

The jQuery append() and prepend() also supports passing in multiple arguments as input.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Append or Prepend Multiple Elements in jQuery</title>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>

$(document).ready(function(){

$("button").click(function(){

var newHeading = "<h1>Important Note:</h1>";

var newParagraph = document.createElement("p");

newParagraph.innerHTML = "<em>Lorem Ipsum is dummy text...</em>";

var newImage = $('<img src="/examples/images/smiley.png" alt="Symbol">');

$("body").append(newHeading, newParagraph, newImage);

});

});

</script>

</head>

<body>

<button type="button">Insert Contents</button>

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam eu sem tempor, varius quam at, luctus
dui. Mauris magna metus, dapibus nec turpis vel, semper malesuada ante, metus ac nisl bibendum.</p>

</body>

</html>

jQuery before() Method

The jQuery before() method is used to insert content before the selected elements.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Inserting HTML Contents Before or After the Elements in jQuery</title>


<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>

$(document).ready(function(){

// Add content after a div container on document ready

$("#container").after("<p>&mdash; The End &mdash;</p>");

// Add content before a div container on document ready

$("#container").before("<p>&mdash; Demo Text &mdash;</p>");

// Add content after heading on button click

$("button.insert-after").click(function(){

$("h1").after('<img src="/examples/images/marker-right.gif" alt="Symbol">');

});

// Add content before heading on button click

$("button.insert-before").click(function(){

$("h1").before('<img src="/examples/images/marker-left.gif" alt="Symbol">');

});

});

</script>

<style>

h1{

display: inline-block; /* To place marker image and heading in one line */

body{

text-align: center;

</style>

</head>

<body>

<h1>Hello World</h1>

<hr>

<button type="button" class="insert-before">Insert Before</button>

<button type="button" class="insert-after">Insert After</button>

<hr>
<div id="container">

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam eu sem tempor, varius quam at, luctus
dui. Mauris magna metus, dapibus nec turpis vel, semper malesuada ante. Vestibulum id metus ac nisl bibendum
scelerisque non non purus. Suspendisse varius nibh non aliquet sagittis. In tincidunt orci sit amet elementum
vestibulum. Vivamus fermentum in arcu in aliquam. Quisque aliquam porta odio in fringilla. Vivamus nisl leo, blandit at
bibendum eu, tristique eget risus. Integer aliquet quam ut elit suscipit, id interdum neque porttitor. Integer faucibus
ligula.</p>

<p>Quis quam ut magna consequat faucibus. Pellentesque eget nisi a mi suscipit tincidunt. Ut tempus
dictum risus. Pellentesque viverra sagittis quam at mattis. Suspendisse potenti. Aliquam sit amet gravida nibh, facilisis
gravida odio. Phasellus auctor velit at lacus blandit, commodo iaculis justo viverra. Etiam vitae est arcu. Mauris vel
congue dolor. Aliquam eget mi mi. Fusce quam tortor, commodo ac dui quis, bibendum viverra erat. Maecenas mattis
lectus enim, quis tincidunt dui molestie euismod. Curabitur et diam tristique, accumsan nunc eu, hendrerit tellus.</p>

</div>

</body>

</html>

jQuery wrap() Method

The jQuery wrap() method is used to wrap an HTML structure around the selected elements.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Wrapping HTML Around the Elements in jQuery</title>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>

$(document).ready(function(){

// Wrap div container with another div on document ready

$(".container").wrap('<div class="wrapper"></div>');

// Wrap paragraph's content on button click

$("button").click(function(){

$("p").contents().wrap("<em><b></b></em>");

});

});

</script>

<style>

.wrapper{

padding: 20px;

background: #f0e68c;
margin: 10px 0;

.container{

padding: 15px;

background: #fff;

font-size: 24px;

</style>

</head>

<body>

<button type="button">Wrap Demo Text</button>

<div class="container">

<p>This is demo text.</p>

</div>

</body>

</html>

jQuery Remove Elements & Attribute

jQuery Remove Elements or Contents

jQuery provides handful of methods, such as empty(), remove(), unwrap() etc. to remove existing HTML
elements or contents from the document.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Removing the Contents of the Elements in jQuery</title>

<style>

.container{

padding: 10px;

background: #f0e68C;

border: 1px solid #bead18;

</style>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>
$(document).ready(function(){

// Empty container div on button click

$("button").click(function(){

$(".container").empty();

});

});

</script>

</head>

<body>

<div class="container">

<h1>Hello World!</h1>

<p class="hint"><strong>Note:</strong> If you click the following button it will remove all the contents
of the container div including the button.</p>

<button type="button">Empty Container</button>

</div>

</body>

</html>

jQuery remove() Method

The jQuery remove() method removes the selected elements from the DOM as well as everything inside it.

Example:-

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Removing the Elements from DOM in jQuery</title>

<style>

.container{

padding: 10px;

background: #f0e68C;

border: 1px solid #bead18;

</style>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>

$(document).ready(function(){
// Removes paragraphs with class "hint" from DOM on button click

$("button").click(function(){

$("p.hint").remove();

});

});

</script>

</head>

<body>

<div class="container">

<h1>Hello World!</h1>

<p class="hint"><strong>Note:</strong> If you click the following button it will remove this
paragraph.</p>

<button type="button">Remove Hint Paragraph</button>

</div>

</body>

</html>

jQuery unwrap() Method

The jQuery unwrap() method removes the parent elements of the selected elements from the DOM. This is
typically the inverse of the wrap() method.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Removing the Parents of the Elements from DOM in jQuery</title>

<style>

.container{

padding: 10px;

background: #f0e68C;

border: 1px solid #bead18;

</style>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>

$(document).ready(function(){

// Removes the paragraph's parent element on button click


$("button").click(function(){

$("p").unwrap();

});

});

</script>

</head>

<body>

<div class="container">

<h1>Hello World!</h1>

<p class="hint"><strong>Note:</strong> If you click the following button it will remove the parent
element of this paragraph.</p>

<button type="button">Remove Paragraph's Parent</button>

</div>

</body>

</html>

jQuery removeAttr() Method

The jQuery removeAttr() method removes an attribute from the selected elements.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Removing an Attribute from the Elements in jQuery</title>

<style>

a{

font-size: 18px;

margin-right: 20px;

</style>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>

$(document).ready(function(){

// Removes the hyperlink's href attribute on button click

$("button").click(function(){

$("a").removeAttr("href");
});

});

</script>

</head>

<body>

<div class="container">

<p>

<a href="https://www.abc.com/">Home</a>

<a href="https:// www.abc.com /about-us.php">About</a>

<a href="https:// www.abc.com /contact-us.php">Contact</a>

</p>

<button type="button">Remove Attribute</button>

</div>

</body>

</html>

jQuery Add and Remove CSS Classes


jQuery CSS Classes Manipulation

jQuery provides several methods, such as addClass(), removeClass(), toggleClass(), etc. to manipulate the CSS
classes assigned to HTML elements.

jQuery addClass() Method

The jQuery addClass() method adds one or more classes to the selected elements.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Adding a Class to the Elements in jQuery</title>

<style>

.page-header{

color: red;

text-transform: uppercase;

.highlight{
background: yellow;

.hint{

font-style: italic;

</style>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>

$(document).ready(function(){

$("button").click(function(){

$("h1").addClass("page-header");

$("p.hint").addClass("highlight");

});

});

</script>

</head>

<body>

<h1>Demo Text</h1>

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit...</p>

<p class="hint"><strong>Tip:</strong> Lorem Ipsum is dummy text.</p>

<button type="button">Add Class</button>

</body>

</html>

jQuery removeClass() Method

Similarly, you can remove the classes from the elements using the jQuery removeClass() method. The
removeClass() method can remove a single class, multiple classes, or all classes at once from the selected elements.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Removing Classes from the Elements in jQuery</title>

<style>

.page-header{

color: red;
text-transform: uppercase;

.highlight{

background: yellow;

.hint{

font-style: italic;

</style>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>

$(document).ready(function(){

$("button").click(function(){

$("h1").removeClass("page-header");

$("p").removeClass("hint highlight");

});

});

</script>

</head>

<body>

<h1 class="page-header">Demo Text</h1>

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit...</p>

<p class="hint highlight"><strong>Tip:</strong> Lorem Ipsum is dummy text.</p>

<button type="button">Remove Class</button>

</body>

</html>

jQuery toggleClass() Method

The jQuery toggleClass() add or remove one or more classes from the selected elements in such a way that if
the selected element already has the class, then it is removed; if an element does not have the class, then it is added
i.e. toggle classes.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Toggle the Classes of the Elements in jQuery</title>


<style>

p{

padding: 10px;

cursor: pointer;

font: bold 16px sans-serif;

.highlight{

background: yellow;

</style>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>

$(document).ready(function(){

$("p").click(function(){

$(this).toggleClass("highlight");

});

});

</script>

</head>

<body>

<p>Click on me to toggle highlighting.</p>

<p class="highlight">Click on me to toggle highlighting.</p>

<p>Click on me to toggle highlighting.</p>

</body>

</html>

jQuery css() Method


The jQuery css() method is used to get the computed value of a CSS property or set one or more CSS properties
for the selected elements. jQuery Get and Set CSS Properties

$(selector).css("propertyName");

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">
<title>jQuery Get the Value of a CSS Property</title>

<style>

div{

width: 100px;

height: 100px;

margin: 10px;

cursor: pointer;

display: inline-block;

</style>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>

$(document).ready(function(){

$("div").click(function(){

var color = $(this).css("background-color");

$("#result").html(color);

});

});

</script>

</head>

<body>

<div style="background-color:orange;"></div>

<div style="background-color:#ee82ee;"></div>

<div style="background-color:rgb(139,205,50);"></div>

<div style="background-color:#f00;"></div>

<p>The computed background-color property value of this DIV element is: <b id="result"></b></p>

</body>

</html>

Set a Single CSS Property and Value

$(selector).css("propertyName", "value");

<!DOCTYPE html>

<html lang="en">

<head>
<meta charset="utf-8">

<title>jQuery Set the Value of a CSS Property</title>

<style>

.box{

width: 100px;

height: 100px;

margin: 10px;

cursor: pointer;

border: 1px solid #cdcdcd;

display: inline-block;

</style>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>

$(document).ready(function(){

$(".box").click(function(){

$(this).css("background-color", "blue");

});

});

</script>

</head>

<body>

<div class="box"></div>

<div class="box"></div>

<div class="box"></div>

<div class="box"></div>

<p><strong>Note:</strong> Click inside the empty box to fill the background color.</p>

</body>

</html>

Set Multiple CSS Properties and Values

$(selector).css({"propertyName":"value", "propertyName":"value", ...});

<!DOCTYPE html>

<html lang="en">
<head>

<meta charset="utf-8">

<title>jQuery Set the Values of Multiple CSS Properties</title>

<style>

p{

font-size: 18px;

font-family: Arial, sans-serif;

</style>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>

$(document).ready(function(){

$("button").click(function(){

$("p").css({"background-color": "yellow", "padding": "20px"});

});

});

</script>

</head>

<body>

<h1>This is a heading</h1>

<p style="background-color:orange;">This a paragraph.</p>

<p style="background-color:#ee82ee;">This is another paragraph.</p>

<p style="background-color:rgb(139,205,50);">This is none more paragraph.</p>

<p>This is one last paragraph.</p>

<button type="button">Add CSS Styles</button>

</body>

</html>

jQuery Dimensions
We will learn how to get or set dimensions of an element's box such as width and height using jQuery.

Understanding the jQuery Dimensions

jQuery provides several methods, such as height(), innerHeight(), outerHeight(), width(), innerWidth() and
outerWidth() to get and set the CSS dimensions for the elements.
jQuery width() and height() Methods

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>jQuery Get Width and Height of an Element</title>

<style>

#box{

width: 300px;

height: 200px;

padding: 25px;

text-align: justify;

border: 10px solid #c6b51a;

background: #f0e68c;

margin: 15px;

</style>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>

$(document).ready(function(){

$("button").click(function(){

var divWidth = $("#box").width();

var divHeight = $("#box").height();

$("#result").html("Width: " + divWidth + ", " + "Height: " + divHeight);

});

});

</script>
</head>

<body>

<div id="box">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam eu sem tempor, varius quam
at, luctus dui. Mauris magna metus, dapibus nec turpis vel, semper malesuada ante. Vestibulum id metus ac nisl
bibendum scelerisque non non purus. Suspendisse varius nibh non aliquet sagittis. In tincidunt orci sit amet
elementum vestibulum. Vivamus fermentum in arcu in aliquam. Quisque aliquam porta odio in fringilla non purus nisld
Dapibus nec turpis vel, semper malesuada ant.</div>

<button type="button">Get Width and Height</button>

<p id="result"></p>

</body>

</html>

jQuery innerWidth() and innerHeight() Methods

The jQuery innerWidth() and innerHeight() methods get or set the inner width and the inner height of the
element respectively.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>jQuery Get Inner-Width and Inner-Height of an Element</title>

<style>

#box{

width: 300px;

height: 200px;

padding: 25px;

text-align: justify;

border: 10px solid #c6b51a;

background: #f0e68c;

margin: 15px;

</style>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>

$(document).ready(function(){

$("button").click(function(){

var divWidth = $("#box").innerWidth();

var divHeight = $("#box").innerHeight();


$("#result").html("Inner Width: " + divWidth + ", " + "Inner Height: " + divHeight);

});

});

</script>

</head>

<body>

<div id="box">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam eu sem tempor, varius quam
at, luctus dui. Mauris magna metus, dapibus nec turpis vel, semper malesuada ante. Vestibulum id metus ac nisl
bibendum scelerisque non non purus. Suspendisse varius nibh non aliquet sagittis. In tincidunt orci sit amet
elementum vestibulum. Vivamus fermentum in arcu in aliquam. Quisque aliquam porta odio in fringilla non purus nisld
Dapibus nec turpis vel, semper malesuada ant.</div>

<button type="button">Get innerWidth and innerHeight</button>

<p id="result"></p>

<hr>

<p><strong>Note:</strong> jQuery <b>innerWidth()</b> includes the CSS properties (<b>width</b> +


<b>padding-left</b> + <b>padding-right</b>), whereas the <b>innerHeight()</b> includes (<b>height</b> +
<b>padding-top</b> + <b>padding-bottom</b>).</p>

</body>

</html>

jQuery Traversing
What is Traversing

The jQuery selectors we've seen so far only allow us to select the elements down the DOM tree.

But there are many occasions when you need to select a parent or ancestor element; that is where jQuery's
DOM traversal methods come into play.

Example:-1

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>HTML DOM Tree Sample</title>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

</head>

<body>

<div class="container">

<h1>Hello World</h1>

<p>This is a <em>simple paragraph</em>.</p>

<ul>

<li>Item One</li>
<li>Item Two</li>

</ul>

</div>

</body>

</html>

jQuery parent() Method

The jQuery parent() method is used to get the direct parent of the selected element.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Selecting the Direct Parent Element in jQuery</title>

<style>

.highlight{

background: yellow;

</style>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>

$(document).ready(function(){

$("li").parent().addClass("highlight");

});

</script>

</head>

<body>

<div class="container">
<h1>Hello World</h1>

<p>This is a <em>simple paragraph</em>.</p>

<ul>

<li>Item One</li>

<li>Item Two</li>

</ul>

</div>

</body>

</html>

jQuery parents() Method

The jQuery parents() method is used to get the ancestors of the selected element.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>jQuery parents() Demo</title>

<style>

*{

margin: 10px;

.frame{

border: 2px solid green;

</style>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>

$(document).ready(function(){

$("li").parents().addClass("frame");

});

</script>

</head>

<body>

<div class="container">

<h1>Hello World</h1>
<p>This is a <em>simple paragraph</em>.</p>

<ul>

<li>Item One</li>

<li>Item Two</li>

</ul>

</div>

</body>

</html>

jQuery children() Method

The jQuery children() method is used to get the direct children of the selected element.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Selecting the Direct Child Elements in jQuery</title>

<style>

.highlight{

background: yellow;

</style>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>

$(document).ready(function(){

$("ul").children().addClass("highlight");

});

</script>

</head>

<body>

<div class="container">

<h1>Hello World</h1>

<p>This is a <em>simple paragraph</em>.</p>

<ul>

<li>Item One</li>

<li>Item Two</li>
</ul>

</div>

</body>

</html>

jQuery siblings() Method

The jQuery siblings() method is used to get the sibling elements of the selected element.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Selecting All the Sibling Elements in jQuery</title>

<style>

.highlight{

background: yellow;

</style>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>

$(document).ready(function(){

$("p").siblings().addClass("highlight");

});

</script>

</head>

<body>

<div class="container">

<h1>Hello World</h1>

<p>This is a <em>simple paragraph</em>.</p>

<ul>

<li>Item One</li>

<li>Item Two</li>

</ul>

</div>

</body>

</html>
jQuery Filtering

Filtering the Elements Selection

jQuery provides several methods such as filter(), first(), last(), eq(), slice(), has(), not(),
etc. that you can use to narrow down the search for elements in a DOM tree.

jQuery first() Method

The jQuery first() method filters the set of matched elements and returns the first
element from the set.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Selecting the First Element in jQuery</title>

<style>

.highlight{

background: yellow;

</style>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>

$(document).ready(function(){

$("ul li").first().addClass("highlight");

});

</script>

</head>

<body>

<h2>Unordered List</h2>

<ul>

<li>First list item</li>

<li>Second list item</li>

<li>Third list item</li>

<li>Fourth list item</li>

</ul>
<hr>

<h2>Another Unordered List</h2>

<ul>

<li>First list item</li>

<li>Second list item</li>

<li>Third list item</li>

<li>Fourth list item</li>

</ul>

</body>

</html>

jQuery last() Method

The jQuery last() method filters the set of matched elements and returns the last element from the set.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Selecting the Last Element in jQuery</title>

<style>

.highlight{

background: yellow;

</style>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>

$(document).ready(function(){

$("ul li").last().addClass("highlight");

});

</script>

</head>

<body>

<h2>Unordered List</h2>

<ul>

<li>First list item</li>


<li>Second list item</li>

<li>Third list item</li>

<li>Fourth list item</li>

</ul>

<hr>

<h2>Another Unordered List</h2>

<ul>

<li>First list item</li>

<li>Second list item</li>

<li>Third list item</li>

<li>Fourth list item</li>

</ul>

</body>

</html>

jQuery eq() Method

The jQuery eq() method filters the set of matched elements and returns only one element with a specified
index number.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Selecting an Element by Index in jQuery</title>

<style>

.highlight{

background: yellow;

</style>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>

$(document).ready(function(){

$("ul li").eq(1).addClass("highlight");

});

</script>

</head>
<body>

<h2>Unordered List</h2>

<ul>

<li>First list item</li>

<li>Second list item</li>

<li>Third list item</li>

<li>Fourth list item</li>

</ul>

<hr>

<h2>Another Unordered List</h2>

<ul>

<li>First list item</li>

<li>Second list item</li>

<li>Third list item</li>

<li>Fourth list item</li>

</ul>

</body>

</html>

jQuery filter() Method

The jQuery filter() method can take the selector or a function as its argument to filters the set of matched
elements based on a specific criteria.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Filtering the Selection of Elements in jQuery via Selectors</title>

<style>

.highlight{

background: yellow;

</style>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>

$(document).ready(function(){

$("ul li").filter(":even").addClass("highlight");
});

</script>

</head>

<body>

<h2>Unordered List</h2>

<ul>

<li>First list item</li>

<li>Second list item</li>

<li>Third list item</li>

<li>Fourth list item</li>

</ul>

<hr>

<h2>Another Unordered List</h2>

<ul>

<li>First list item</li>

<li>Second list item</li>

<li>Third list item</li>

<li>Fourth list item</li>

</ul>

</body>

</html>

jQuery has() Method

The jQuery has() method filters the set of matched elements and returns only those elements that has the
specified descendant element.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Selecting Elements that Contain Specific Child Elements in jQuery</title>

<style>

.highlight{

background: yellow;

</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>

$(document).ready(function(){

$("ul li").has("ul").addClass("highlight");

});

</script>

</head>

<body>

<ul>

<li>Section 1</li>

<li>Section 2</li>

<li>

<ul>

<li>Section 2.1</li>

<li>Section 2.2</li>

<li>Section 2.3</li>

</ul>

</li>

<li>Section 4</li>

</ul>

</body>

</html>

jQuery not() Method

The jQuery not() method filters the set of matched elements and returns all elements that does not met the
specified conditions. It can take the selector or a function as its argument.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Selecting Elements that Doesn't Match a Condition in jQuery</title>

<style>

.highlight{

background: yellow;

</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>

$(document).ready(function(){

$("ul li").not(":even").addClass("highlight");

});

</script>

</head>

<body>

<h2>Unordered List</h2>

<ul>

<li>First list item</li>

<li>Second list item</li>

<li>Third list item</li>

<li>Fourth list item</li>

</ul>

<hr>

<h2>Another Unordered List</h2>

<ul>

<li>First list item</li>

<li>Second list item</li>

<li>Third list item</li>

<li>Fourth list item</li>

</ul>

</body>

</html>

jQuery slice() Method

The jQuery slice() method filters the set of matched elements specified by a range of indices.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Selecting the Elements by Range of Indices in jQuery</title>

<style>

.highlight{

background: yellow;
}

</style>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>

$(document).ready(function(){

$("ul li").slice(0, 2).addClass("highlight");

});

</script>

</head>

<body>

<h2>Unordered List</h2>

<ul>

<li>First list item</li>

<li>Second list item</li>

<li>Third list item</li>

<li>Fourth list item</li>

</ul>

<hr>

<h2>Another Unordered List</h2>

<ul>

<li>First list item</li>

<li>Second list item</li>

<li>Third list item</li>

<li>Fourth list item</li>

</ul>

</body>

</html>

Create Duplicate of the elements with .clone() – jQuery


The .clone() method creates the duplicate of the matched elements. It allows either event
handler will be copy or not, it by default doesn’t copy attached events.

This simplifies your code when you need to make a clone of the group of elements. You don’t have the need
to create each group element and insert it.
Create clone

Call the .clone() method on the selector which you want to copy and insert the newly created element in
your existing HTML layout using append, pretend, insertAfter, etc.

Syntax –

$( selector ).clone();

Example

$( ".txt").clone();

Example

HTML

Created a <div class='input-form'> which have two input element and a button to create copy of <div
class='input-form'> using jQuery.

<html>

<body>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>

$(document).ready(function(){

$('#but_add').click(function(){

// Create clone of <div class='input-form'>

var newel = $('.input-form:last').clone();

// Add after last <div class='input-form'>

$(newel).insertAfter(".input-form:last");

});

$('.txt').focus(function(){

$(this).css('border-color','red');

});

$('.txt').focusout(function(){

$(this).css('border-color','initial');

});

});

</script>

<div class='input-form'>

<input type='text' placeholder='Enter name' id='name_1' class='txt' >


<input type='text' placeholder='Enter email' id='email_1' class='txt' >

</div>

<input type='button' id='but_add' value='Add new'>

</body>

</html>

3. Event handler

It copies the event handler as well while creating the clone. For this pass true in the clone()
method.

By default, it set to false.

$(document).ready(function(){

$('#but_add').click(function(){

// Create clone of <div class='input-form'>

var newel = $('.input-form:last').clone(true);

// Add after last <div class='input-form'>

$(newel).insertAfter(".input-form:last");

});

$('.txt').focus(function(){

$(this).css('border-color','red');

});

$('.txt').focusout(function(){

$(this).css('border-color','initial');

});

});

Clone with create different id

$(document).ready(function(){

$('#but_add').click(function(){

// Selecting last id

var lastname_id = $('.input-form input[type=text]:nth-child(1)').last().attr('id');

var split_id = lastname_id.split('_');


// New index

var index = Number(split_id[1]) + 1;

// Create clone

var newel = $('.input-form:last').clone(true);

// Set id of new element

$(newel).find('input[type=text]:nth-child(1)').attr("id","name_"+index);

$(newel).find('input[type=text]:nth-child(2)').attr("id","email_"+index);

// Set value

$(newel).find('input[type=text]:nth-child(1)').val("name_"+index);

$(newel).find('input[type=text]:nth-child(2)').val("email_"+index);

// Insert element

$(newel).insertAfter(".input-form:last");

});

});

Dealing with form elements


Working of the jQuery get form values
The jQuery get form values can be performed with the help of the val() function
or serializeArray() function; both the functions do not accept any parameters.
Suppose we have a form element in the HTML page containing some form input
elements like input text element and checkbox element.
Example

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<title> This is an example for jQuery get form values </title>
</head>
<body>
<h3> This an example of jQuery get form values : </h3>
<form action = "#myform">
<h3> Please Enter the details : </h3>
<div>
First name : <input type = "text", id = "fname"> <br/> <br/>
Last name : <input type = "text" id = "lname"> <br/> <br/>
Mobile number : <input type = "text" disabled = "disabled" id = "mob" > <br/>
<br/>
Email ID: <input type = "text" id = "eid"> <br/> <br/>
<input type = "submit" id = "subm">
<p> Click to the submit to get the form entered data. </p>
</div>
</form>
<p id = "p1"> </p>
<script>
$(document).ready(function() {
$( "#subm").click(function(){
var fname = $("#fname").val();
var lname = $("#lname").val();
var mob = $("#mob").val();
var eid = $("#eid").val();
$( "#p1" ).append("The first name is : " +fname);
$( "#p1" ).append("<br> The last name is : " +lname);
$( "#p1" ).append("<br> The mobile number is : " +mob);
$( "#p1" ).append("<br> The email id is : " +eid);
});
});
</script>
</body>
</html>
Example 2:-

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<title> This is an example for jQuery get form values </title>
</head>
<body>
<h3> This an example of jQuery get form values : </h3>
<form action = "#">
<h3> Please Enter the details : </h3>
<div>
Name : <input type = "text", name = "name" id = "fname"> <br/> <br/>
Gender : <br />
<input type = "radio" name = "gr" value = "male"/> Male
<input type = "radio" name = "gr" value = "female"/> Female
<br /><br />
<input type = "submit" id = "subm">
<p> Click to the submit to get the form entered data. </p>
</div>
</form>
<p id = "p1"> </p>
<script>
$(document).ready(function() {
$( "#subm").click(function(){
var x = $("form").serializeArray();
$.each(x, function(i, field) {
alert(field.name + " : " + field.value + " ");
});
});
});
</script>
</body>
</html>

Using the JQuey Flags

<html >
<head>
<title></title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#divTitle").addClass("style1");
var flag=true;
function blinkstyle(){
if(flag==true)
{
if($("#divTitle").hasClass("style1"))
$("#divTitle").removeClass("style1");
$("#divTitle").addClass("style2");
flag = false;
}
else {
if ($("#divTitle").hasClass("style2"))
$("#divTitle").removeClass("style2");
$("#divTitle").addClass("style1");
flag = true;
}
}
window.setInterval(blinkstyle,200);
});
</script>
<style type="text/css">
.style1 {
text-align:center;
width:70%;
height:100px;
line-height:100px;
background-color:red;
color:white;
font-family:Tahoma;
font-size:60px;
border:5px solid green;
border-radius:10px;
box-shadow:gray 10px 15px;
}
.style2 {
text-align:center;
width:70%;
height:110px;
line-height:95px;
background-color:yellow;
color:red;
font-family:'Monotype Corsiva';
font-size:100px;
border:7px solid green;
border-radius:20px;
box-shadow:green 10px 15px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div id="divTitle">
<b>Elysium Academy</b>
</div>
</form>
</body>
</html>

JQuery with Effects


jQuery show() and hide() Methods

You can show and hide HTML elements using the jQuery show() and hide() methods.

The hide() method simply sets the inline style display: none for the selected elements.
Conversely, the show() method restores the display properties of the matched set of elements to
whatever they initially were—typically block, inline, or inline-block—before the inline style
display: none was applied to them.

<!DOCTYPE html>

<html lang="en">

<head>
<meta charset="utf-8">

<title>Example of jQuery Show Hide Effects</title>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<style>

p{

padding: 15px;

background: #F0E68C;

</style>

<script>

$(document).ready(function(){

// Hide displayed paragraphs

$(".hide-btn").click(function(){

$("p").hide();

});

// Show hidden paragraphs

$(".show-btn").click(function(){

$("p").show();

});

});

</script>

</head>

<body>

<button type="button" class="hide-btn">Hide Paragraphs</button>

<button type="button" class="show-btn">Show Paragraphs</button>

<p>This is a paragraph.</p>

<p>This is another paragraph.</p>

</body>

</html>
Show & Hide based on Duration

Durations can be specified either using one of the predefined string 'slow' or 'fast', or in
a number of milliseconds, for greater precision; higher values indicate slower animations.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Example of jQuery Animated Show Hide Effects</title>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<style>

p{

padding: 15px;

background: #F0E68C;

</style>

<script>

$(document).ready(function(){

// Hide displayed paragraphs with different speeds

$(".hide-btn").click(function(){

$("p.normal").hide();

$("p.fast").hide("fast");

$("p.slow").hide("slow");

$("p.very-fast").hide(50);

$("p.very-slow").hide(2000);

});

// Show hidden paragraphs with different speeds

$(".show-btn").click(function(){

$("p.normal").show();

$("p.fast").show("fast");
$("p.slow").show("slow");

$("p.very-fast").show(50);

$("p.very-slow").show(2000);

});

});

</script>

</head>

<body>

<button type="button" class="hide-btn">Hide Paragraphs</button>

<button type="button" class="show-btn">Show Paragraphs</button>

<p class="very-fast">This paragraph will show/hide with very fast speed.</p>

<p class="normal">This paragraph will show/hide with default speed.</p>

<p class="fast">This paragraph will show/hide with fast speed.</p>

<p class="slow">This paragraph will show/hide with slow speed.</p>

<p class="very-slow">This paragraph will show/hide with very slow speed.</p>

</body>

</html>

Note: The speed or duration string 'fast' indicates the durations of 200 milliseconds,
while the string 'slow' indicates the durations of 600 milliseconds.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Example of jQuery Show Hide Effects with Callback</title>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<style>

p{

padding: 15px;

background: #F0E68C;

</style>

<script>

$(document).ready(function(){

// Display alert message after hiding paragraphs

$(".hide-btn").click(function(){

$("p").hide("slow", function(){

// Code to be executed

alert("The hide effect is completed.");

});

});

// Display alert message after showing paragraphs

$(".show-btn").click(function(){

$("p").show("slow", function(){

// Code to be executed

alert("The show effect is completed.");

});

});

});

</script>

</head>

<body>

<button type="button" class="hide-btn">Hide Paragraphs</button>

<button type="button" class="show-btn">Show Paragraphs</button>

<p>This is a paragraph.</p>

</body>
</html>

jQuery toggle() Method

The jQuery toggle() method show or hide the elements in such a way that if the element
is initially displayed, it will be hidden; if hidden, it will be displayed (i.e. toggles the visibility).

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Example of jQuery Toggle Effect</title>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<style>

p{

padding: 15px;

background: #F0E68C;

</style>

<script>

$(document).ready(function(){

// Toggles paragraphs display

$(".toggle-btn").click(function(){

$("p").toggle();

});

});

</script>

</head>

<body>

<button type="button" class="toggle-btn">Toggle Paragraphs</button>

<p>This is a paragraph.</p>

<p>This is another paragraph.</p>

</body>
</html>

Slow and fast toggle

<style>

p{

padding: 15px;

background: #F0E68C;

</style>

<script>

$(document).ready(function(){

// Toggles paragraphs with different speeds

$(".toggle-btn").click(function(){

$("p.normal").toggle();

$("p.fast").toggle("fast");

$("p.slow").toggle("slow");

$("p.very-fast").toggle(50);

$("p.very-slow").toggle(2000);

});

});

</script>

</head>

<body>

<button type="button" class="toggle-btn">Toggle Paragraphs</button>

<p class="very-fast">This paragraph will show/hide with very fast speed.</p>

<p class="normal">This paragraph will show/hide with default speed.</p>

<p class="fast">This paragraph will show/hide with fast speed.</p>

<p class="slow">This paragraph will show/hide with slow speed.</p>

<p class="very-slow">This paragraph will show/hide with very slow speed.</p>

</body>
jQuery Fading Effects

jQuery fadeIn() and fadeOut() Methods

You can use the jQuery fadeIn() and fadeOut() methods to display or hide the HTML
elements by gradually increasing or decreasing their opacity.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Example of jQuery Fade-In and Fade-Out Effects</title>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<style>

p{

padding: 15px;

background: #DDA0DD;

</style>

<script>

$(document).ready(function(){

// Fadeing out displayed paragraphs

$(".out-btn").click(function(){

$("p").fadeOut();

});

// Fading in hidden paragraphs

$(".in-btn").click(function(){

$("p").fadeIn();

});

});

</script>
</head>

<body>

<button type="button" class="out-btn">Fade Out Paragraphs</button>

<button type="button" class="in-btn">Fade In Paragraphs</button>

<p>This is a paragraph.</p>

<p>This is another paragraph.</p>

</body>

</html>

fadeIn() and fadeOut() methods to control how long the fading animation will run.
Durations can be specified either using one of the predefined string 'slow' or 'fast', or in a
number of milliseconds;

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Example of jQuery Fade-In and Fade-Out Effects with Different Speeds</title>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<style>

p{

padding: 15px;

background: #DDA0DD;

</style>

<script>

$(document).ready(function(){

// Fading out displayed paragraphs with different speeds

$(".out-btn").click(function(){

$("p.normal").fadeOut();

$("p.fast").fadeOut("fast");

$("p.slow").fadeOut("slow");

$("p.very-fast").fadeOut(50);
$("p.very-slow").fadeOut(2000);

});

// Fading in hidden paragraphs with different speeds

$(".in-btn").click(function(){

$("p.normal").fadeIn();

$("p.fast").fadeIn("fast");

$("p.slow").fadeIn("slow");

$("p.very-fast").fadeIn(50);

$("p.very-slow").fadeIn(2000);

});

});

</script>

</head>

<body>

<button type="button" class="out-btn">Fade Out Paragraphs</button>

<button type="button" class="in-btn">Fade In Paragraphs</button>

<p class="very-fast">This paragraph will fade in/out with very fast speed.</p>

<p class="normal">This paragraph will fade in/out with default speed.</p>

<p class="fast">This paragraph will fade in/out with fast speed.</p>

<p class="slow">This paragraph will fade in/out with slow speed.</p>

<p class="very-slow">This paragraph will fade in/out with very slow speed.</p>

</body>

</html>

jQuery Sliding Effects


jQuery slideUp() and slideDown() Methods

The jQuery slideUp() and slideDown() methods is used to hide or show the HTML
elements by gradually decreasing or increasing their height (i.e. by sliding them up or down).

<!DOCTYPE html>

<html lang="en">
<head>

<meta charset="utf-8">

<title>Example of jQuery Slide-Up and Slide-Down Effects</title>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<style>

p{

padding: 15px;

background: #B0C4DE;

</style>

<script>

$(document).ready(function(){

// Slide up displayed paragraphs

$(".up-btn").click(function(){

$("p").slideUp();

});

// Slide down hidden paragraphs

$(".down-btn").click(function(){

$("p").slideDown();

});

});

</script>

</head>

<body>

<button type="button" class="up-btn">Slide Up Paragraphs</button>

<button type="button" class="down-btn">Slide Down Paragraphs</button>

<p>This is a paragraph.</p>

<p>This is another paragraph.</p>

</body>

</html>
slideUp() and slideDown() methods to control how long the slide animation will run.
Durations can be specified either using one of the predefined string 'slow' or 'fast', or in a
number of milliseconds;

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Example of jQuery Slide-Up and Slide-Down Effects with Different Speeds</title>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<style>

p{

padding: 15px;

background: #B0C4DE;

</style>

<script>

$(document).ready(function(){

// Sliding up displayed paragraphs with different speeds

$(".up-btn").click(function(){

$("p.normal").slideUp();

$("p.fast").slideUp("fast");

$("p.slow").slideUp("slow");

$("p.very-fast").slideUp(50);

$("p.very-slow").slideUp(2000);

});

// Sliding down hidden paragraphs with different speeds

$(".down-btn").click(function(){

$("p.normal").slideDown();

$("p.fast").slideDown("fast");
$("p.slow").slideDown("slow");

$("p.very-fast").slideDown(50);

$("p.very-slow").slideDown(2000);

});

});

</script>

</head>

<body>

<button type="button" class="up-btn">Slide Up Paragraphs</button>

<button type="button" class="down-btn">Slide Down Paragraphs</button>

<p class="very-fast">This paragraph will fade in/out with very fast speed.</p>

<p class="normal">This paragraph will fade in/out with default speed.</p>

<p class="fast">This paragraph will fade in/out with fast speed.</p>

<p class="slow">This paragraph will fade in/out with slow speed.</p>

<p class="very-slow">This paragraph will fade in/out with very slow speed.</p>

</body>

</html>

jQuery slideToggle() Method

The jQuery slideToggle() method show or hide the selected elements by animating their
height in such a way that if the element is initially displayed, it will be slide up; if hidden, it will be
slide down i.e. toggles between the slideUp() and slideDown() methods.

<script>

$(document).ready(function(){

// Toggles paragraphs display with sliding

$(".toggle-btn").click(function(){

$("p").slideToggle();

});

});

</script>
jQuery Animation Effects

jQuery animate() Method

The jQuery animate() method is used to create custom animations. The animate()
method is typically used to animate numeric CSS properties, for example, width, height, margin,
padding, opacity, top, left, etc. but the non-numeric properties such as color or background-color
cannot be animated using the basic jQuery functionality.

Syntax

The basic syntax of the jQuery animate() method can be given with:

$(selector).animate({ properties }, duration, callback);

The parameters of the animate() method have the following meanings:

The required properties parameter defines the CSS properties to be animated.

The optional duration parameter specifies how long the animation will run. Durations
can be specified either using one of the predefined string 'slow' or 'fast', or in a number of
milliseconds; higher values indicate slower animations.

The optional callback parameter is a function to call once the animation is complete.

Here's a simple example of the jQuery animate() method that animates an image from
its original position to the right by 300 pixels on click of the button.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Example of jQuery Animation Effects</title>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<style>

img{

position: relative; /* Required to move element */

</style>

<script>
$(document).ready(function(){

$("button").click(function(){

$("img").animate({

left: 300

});

});

});

</script>

</head>

<body>

<button type="button">Start Animation</button>

<p>

<img src="images12.jpg" alt="myimage">

</p>

</body>

</html>

Animate Multiple Properties At Once

You can also animate multiple properties of an element together at the same time using
the animate() method. All the properties animated simultaneously without any delay.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Example of jQuery Multiple Properties Animation</title>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<style>

.box{

width: 100px;

height: 100px;
background: #9d7ede;

margin-top: 30px;

border-style: solid; /* Required to animate border width */

border-color: #6f40ce;

</style>

<script>

$(document).ready(function(){

$("button").click(function(){

$(".box").animate({

width: "300px",

height: "300px",

marginLeft: "150px",

borderWidth: "10px",

opacity: 0.5

});

});

});

</script>

</head>

<body>

<button type="button">Start Animation</button>

<div class="box"></div>

</body>

</html>

Animate Multiple Properties One by One or Queued Animations

<!DOCTYPE html>

<html lang="en">

<head>
<meta charset="utf-8">

<title>Example of jQuery Queued Animation</title>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<style>

.box{

width: 100px;

height: 100px;

background: #9d7ede;

margin-top: 30px;

border-style: solid; /* Required to animate border width */

border-color: #6f40ce;

</style>

<script>

$(document).ready(function(){

$("button").click(function(){

$(".box")

.animate({width: "300px"})

.animate({height: "300px"})

.animate({marginLeft: "150px"})

.animate({borderWidth: "10px"})

.animate({opacity: 0.5});

});

});

</script>

</head>

<body>

<button type="button">Start Animation</button>

<div class="box"></div>

</body>

</html>
jQuery Stop Animations

Will learn how to stop running animations using jQuery.

jQuery stop() Method

The jQuery stop() method is used to stop the jQuery animations or effects currently
running on the selected elements before it completes.

The basic syntax of the jQuery stop() method can be given with:

$(selector).stop(stopAll, goToEnd);

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>jQuery Stop Currently Running Animations</title>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<style>

img{

position: relative; /* Required to move element */

</style>

<script>

$(document).ready(function(){

// Start animation

$(".start-btn").click(function(){

$("img").animate({left: "+=150px"}, 2000);

});

// Stop running animation

$(".stop-btn").click(function(){

$("img").stop();

});
// Start animation in the opposite direction

$(".back-btn").click(function(){

$("img").animate({left: "-=150px"}, 2000);

});

// Reset to default

$(".reset-btn").click(function(){

$("img").animate({left: "0"}, "fast");

});

});

</script>

</head>

<body>

<button type="button" class="start-btn">Start</button>

<button type="button" class="stop-btn">Stop</button>

<button type="button" class="back-btn">Back</button>

<button type="button" class="reset-btn">Reset</button>

<p>

<img src="/examples/images/mushroom.jpg" alt="Mushroom">

</p>

</body>

</html>

Creating Smooth Hover Effect

While creating the animated hover effect one of the common problem you may face is
multiple queued animations, when you place and remove the mouse cursor rapidly.

Because, in this situation mouseenter or mouseleave events are triggered quickly before
the animation complete. To avoid this problem and create a nice and smooth hover effect you
can add the stop(true, true) to the method chain, like this:

<!DOCTYPE html>
<html lang="en">

<head>

<meta charset="utf-8">

<title>jQuery Smooth Hover Effect</title>

<style>

.box{

width: 500px;

height: 300px;

border: 5px solid #000;

</style>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>

$(document).ready(function(){

$(".box").hover(function(){

$(this).find("img").stop(true, true).fadeOut();

}, function(){

$(this).find("img").stop(true, true).fadeIn();

});

});

</script>

</head>

<body>

<div class="box">

<img src="images12.jpg" alt="Cloudy Sky">

</div>

<p><strong>Note:</strong> Place and remove the mouse pointer over the image to
see the effect.</p>

</body>

</html>
jQuery Ajax
Ajax stands for Asynchronous Javascript And Xml. Ajax is just a means of loading data
from the server to the web browser without reloading the whole page.

Note: Ajax is not a new technology, in fact, Ajax is not even really a technology at all. Ajax
is just a term to describe the process of exchanging data from a web server asynchronously
through JavaScript, without a page refresh.

Ajax with jQuery


Different browsers implement the Ajax differently that means if you're adopting the typical
JavaScript way to implement the Ajax you have to write the different code for different browsers to ensure
that Ajax would work cross-browser.

JQuery simplifies the process of implementing Ajax by taking care of those browser differences.

It offers simple methods such as load(), $.get(), $.post(), etc. to implement the Ajax that works
seamlessly across all the browsers.

Tip: Ajax requests are triggered by the JavaScript code; your code sends a request to a URL, and
when the request completes, a callback function can be triggered to handle the response.

Further, since the request is asynchronous, the rest of your code continues to execute while the
request is being processed.

jQuery load() Method

The jQuery load() method loads data from the server and place the returned HTML into
the selected element
$(selector).load(URL, data, complete);

The parameters of the load() method has the following meaning:

• The required URL parameter specifies the URL of the file you want to load.

• The optional data parameter specifies a set of query string (i.e. key/value pairs) that is sent to the web
server along with the request.

• The optional complete parameter is basically a callback function that is executed when the request
completes. The callback is fired once for each selected element.

Let's put this method into real use. Create a blank HTML file "test-content.html" and save it
somewhere in your web server. Now place the following HTML code inside of this file:

Create a folder in D:\>md test

Change Folder

D:\>cd test

D:\test>
Write a program named test-content.html under d:\test> folder

Test-content.html

<h1>Simple Ajax Demo</h1>

<p id="hint">This is a simple example of Ajax loading.</p>

<p><img src="sky.jpg" alt="Cloudy Sky"></p>

Load-demo.html

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>jQuery load() Demo</title>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>

$(document).ready(function(){

$("button").click(function(){

$("#box").load("test-content.html");

});

});

</script>

</head>

<body>

<div id="box">

<h2>Click button to load new content inside DIV box</h2>

</div>

<button type="button">Load Content</button>

</body>

</html>

Write another program in same folder named load-demo.html used to load the previous file
content and display the output your browser via ajax load method.
Step 1: placed two files & and related images in your test folder

Step 2: install http server in your current folder

D:\test>npm install http-server

Step3: start http server

D:\test> http-server

Once start your show like this

Starting up http-server, serving ./

http-server version: 14.1.1

http-server settings:

CORS: disabled

Cache: 3600 seconds

Connection Timeout: 120 seconds

Directory Listings: visible

AutoIndex: visible

Serve GZIP Files: false

Serve Brotli Files: false

Default File Extension: none

Available on:

http://192.168.4.163:8081

http://127.0.0.1:8081

Hit CTRL-C to stop the server

Step4: Open browser

Type the following url based on your localhost and port number

http://127.0.0.1:8081

Step5: Look at your browser it will show your html file

Click the file named load-demo.html


Further, the callback function can have three different parameters:

responseTxt — Contains the resulting content if the request succeeds.

statusTxt — Contains the status of the request such as success or error.

jqXHR — Contains the XMLHttpRequest object.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>jQuery load() Demo</title>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>

$(document).ready(function(){

$("button").click(function(){

$("#box").load("test-content.html", function(responseTxt, statusTxt, jqXHR){

if(statusTxt == "success"){

alert("New content loaded successfully!");

if(statusTxt == "error"){

alert("Error: " + jqXHR.status + " " + jqXHR.statusText);

});

});

});

</script>

</head>

<body>

<div id="box">

<h2>Click button to load new content inside DIV box</h2>

</div>

<button type="button">Load Content</button>


</body>

</html>

You might also like