0% found this document useful (0 votes)
7 views48 pages

J Query Tutorial

jQuery is a popular and lightweight JavaScript library that simplifies programming tasks such as DOM manipulation, event handling, and AJAX calls. It allows developers to write less code to achieve more functionality and is widely used by major companies. The document provides examples of jQuery syntax, selectors, event methods, and effects like hide, show, fadeIn, and fadeOut.

Uploaded by

amallallu.ipcs
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views48 pages

J Query Tutorial

jQuery is a popular and lightweight JavaScript library that simplifies programming tasks such as DOM manipulation, event handling, and AJAX calls. It allows developers to write less code to achieve more functionality and is widely used by major companies. The document provides examples of jQuery syntax, selectors, event methods, and effects like hide, show, fadeIn, and fadeOut.

Uploaded by

amallallu.ipcs
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

JQUERY:

jQuery is a JavaScript Library.

jQuery greatly simplifies JavaScript programming.

jQuery is easy to learn.

<!DOCTYPE html>
<html>
<head>
<script src="[Link]
<script>
$(document).ready(function(){
$("p").click(function(){
$(this).hide();
});
});
</script>
</head>
<body>

<p>If you click on me, I will disappear.</p>


<p>Click me away!</p>
<p>Click me too!</p>

</body>
</html>

What is jQuery?
jQuery is a lightweight, "write less, do more", JavaScript library.

The purpose of jQuery is to make it much easier to use JavaScript on your


website.

jQuery takes a lot of common tasks that require many lines of JavaScript code
to accomplish, and wraps them into methods that you can call with a single
line of code.

jQuery also simplifies a lot of the complicated things from JavaScript, like
AJAX calls and DOM manipulation.

The jQuery library contains the following features:


● HTML/DOM manipulation
● CSS manipulation
● HTML event methods
● Effects and animations
● AJAX
● Utilities

Tip: In addition, jQuery has plugins for almost any task out there.

Why jQuery?
There are lots of other JavaScript libraries out there, but jQuery is probably
the most popular, and also the most extendable.

Many of the biggest companies on the Web use jQuery, such as:

● Google
● Microsoft
● IBM
● Netflix

Adding jQuery to Your Web Pages


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

● Download the jQuery library from [Link]


● Include jQuery from a CDN, like Google

<!DOCTYPE html>
<html>
<head>
<script src="[Link]
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
</script>
</head>
<body>

<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

<button>Click me</button>

</body>
</html>

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()

$(“p”).hide;

● A $ sign to define/access jQuery


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

Function functionname ()

Function sum()

Examples:

$(this).hide() - hides the current element.

$("p").hide() - hides all <p> elements.

$(".test").hide() - hides all elements with class="test".

$("#test").hide() - hides the element with id="test".

jQuery Selectors
jQuery selectors are one of the most important parts of the jQuery library.

jQuery selectors allow you to select and manipulate HTML element(s).

jQuery selectors are used to "find" (or select) HTML elements based on their
name, id, classes, types, attributes, values of attributes and much more. It's
based on the existing CSS Selectors, and in addition, it has some own custom
selectors.

All selectors in jQuery start with the dollar sign and parentheses: $().
The element Selector
The jQuery element selector selects elements based on the element name.

You can select all <p> elements on a page like this:

$("p")

Example

When a user clicks on a button, all <p> elements will be hidden:

<!DOCTYPE html>
<html>
<head>
<script src="[Link]
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
</script>
</head>
<body>

<h2>This is a heading</h2>

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

<button>Click me to hide paragraphs</button>

</body>
</html>

The #id Selector


The jQuery #id selector uses the id attribute of an HTML tag to find the
specific element.

An id should be unique within a page, so you should use the #id selector
when you want to find a single, unique element.

To find an element with a specific id, write a hash character, followed by the
id of the HTML element:
$("#test")

Example:

<!DOCTYPE html>
<html>
<head>
<script
src="[Link]
[Link]"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#test").hide();
});
});
</script>
</head>
<body>

<h2>This is a heading</h2>

<p>This is a paragraph.</p>
<p id="test">This is another paragraph.</p>

<button>Click me</button>

</body>
</html>

What are Events?


All the different visitors' actions that a web page can respond to are called
events.

An event represents the precise moment when something happens.

Examples:

● moving a mouse over an element


● selecting a radio button
● clicking on an element

The term "fires/fired" is often used with events. Example: "The keypress
event is fired, the moment you press a key".
jQuery Syntax For Event Methods
In jQuery, most DOM events have an equivalent jQuery method.

To assign a click event to all paragraphs on a page, you can do this:

$("p").click();

$("p").click(function(){
// action goes here!!
});

Commonly Used jQuery Event Methods


$(document).ready()

The $(document).ready() method allows us to execute a function when the


document is fully loaded.

click()

The click() method attaches an event handler function to an HTML


element.

The function is executed when the user clicks on the HTML element.

The following example says: When a click event fires on a <p> element; hide
the current <p> element:

<!DOCTYPE html>

<html>

<head>

<script
src="[Link]
script>

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

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

$(this).hide();

});

});

</script>

</head>

<body>

<p>If you click on me, I will disappear.</p>

<p>Click me away!</p>

<p>Click me too!</p>

</body>

</html>

dblclick()

The dblclick() method attaches an event handler function to an HTML


element.

The function is executed when the user double-clicks on the HTML element:

<!DOCTYPE html>

<html>

<head>

<script
src="[Link]
script>

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

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

$(this).hide();

});

});

</script>

</head>

<body>

<p>If you double-click on me, I will disappear.</p>

<p>Click me away!</p>

<p>Click me too!</p>

</body>

</html>

mouseenter()

The mouseenter() method attaches an event handler function to an HTML


element.

The function is executed when the mouse pointer enters the HTML element:

<!DOCTYPE html>
<html>
<head>
<script
src="[Link]
[Link]"></script>
<script>
$(document).ready(function(){
$("#p1").mouseenter(function(){
alert("You entered p1!");
});
});
</script>
</head>
<body>

<p id="p1">Enter this paragraph.</p>

</body>
</html>

mouseleave()

The mouseleave() method attaches an event handler function to an HTML


element.

The function is executed when the mouse pointer leaves the HTML element:

<!DOCTYPE html>
<html>
<head>
<script
src="[Link]
[Link]"></script>
<script>
$(document).ready(function(){
$("#p1").mouseleave(function(){
alert("Bye! You now leave p1!");
});
});
</script>
</head>
<body>

<p id="p1">This is a paragraph.</p>

</body>
</html>

mousedown()

The mousedown() method attaches an event handler function to an HTML


element.
The function is executed, when the left, middle or right mouse button is
pressed down, while the mouse is over the HTML element:

<!DOCTYPE html>
<html>
<head>
<script
src="[Link]
[Link]"></script>
<script>
$(document).ready(function(){
$("#p1").mousedown(function(){
alert("Mouse down over p1!");
});
});
</script>
</head>
<body>

<p id="p1">This is a paragraph.</p>

</body>
</html>

mouseup()

The mouseup() method attaches an event handler function to an HTML


element.

The function is executed, when the left, middle or right mouse button is
released, while the mouse is over the HTML element:

<!DOCTYPE html>
<html>
<head>
<script
src="[Link]
[Link]"></script>
<script>
$(document).ready(function(){
$("#p1").mouseup(function(){
alert("Mouse up over p1!");
});
});
</script>
</head>
<body>

<p id="p1">This is a paragraph.</p>

</body>
</html>

hover()

The hover() method takes two functions and is a combination of the


mouseenter() and mouseleave() methods.

The first function is executed when the mouse enters the HTML element, and
the second function is executed when the mouse leaves the HTML element:

<!DOCTYPE html>
<html>
<head>
<script
src="[Link]
[Link]"></script>
<script>
$(document).ready(function(){
$("#p1").hover(function(){
alert("You entered p1!");
},
function(){
alert("Bye! You now leave p1!");
});
});
</script>
</head>
<body>

<p id="p1">This is a paragraph.</p>

</body>
</html>

focus()

The focus() method attaches an event handler function to an HTML form


field.

The function is executed when the form field gets focus:


<!DOCTYPE html>
<html>
<head>
<script
src="[Link]
[Link]"></script>
<script>
$(document).ready(function(){
$("input").focus(function(){
$(this).css("background-color", "yellow");
});
$("input").blur(function(){
$(this).css("background-color", "green");
});
});
</script>
</head>
<body>

Name: <input type="text" name="fullname"><br>


Email: <input type="text" name="email">

</body>
</html>

blur()

The blur() method attaches an event handler function to an HTML form


field.

The function is executed when the form field loses focus:

/******* To Check********/
<!DOCTYPE html>
<html>
<head>
<script
src="[Link]
[Link]"></script>
<script>
$(document).ready(function(){
$("input").focus(function(){
$(this).css("background-color", "yellow");
});
$("input").blur(function(){
$(this).css("background-color", "green");
});
});
</script>
</head>
<body>

Name: <input type="text" name="fullname"><br>


Email: <input type="text" name="email">

</body>
</html>

The on() Method


The on() method attaches one or more event handlers for the selected
elements.

Attach a click event to a <p> element:

<!DOCTYPE html>
<html>
<head>
<script
src="[Link]
[Link]"></script>
<script>
$(document).ready(function(){
$("p").on("click", function(){
$(this).hide();
});
});
</script>
</head>
<body>

<p>If you click on me, I will disappear.</p>


<p>Click me away!</p>
<p>Click me too!</p>

</body>
</html>

jQuery Effects - Hide and Show


<!DOCTYPE html>
<html>
<head>
<script
src="[Link]
[Link]"></script>
<script>
$(document).ready(function(){
$("#hide").click(function(){
$("p").hide();
});
$("#show").click(function(){
$("p").show();
});
});
</script>
</head>
<body>

<p>If you click on the "Hide" button, I will disappear.</p>

<button id="hide">Hide</button>
<button id="show">Show</button>

</body>
</html>

The optional speed parameter specifies the speed of the hiding/showing, and
can take the following values: "slow", "fast", or milliseconds.

The optional callback parameter is a function to be executed after the


hide() or show() method completes (you will learn more about callback
functions in a later chapter).

The following example demonstrates the speed parameter with hide():

<!DOCTYPE html>
<html>
<head>
<script
src="[Link]
[Link]"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").hide(1000);
});
});
</script>
</head>
<body>

<button>Hide</button>

<p>This is a paragraph with little content.</p>


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

</body>
</html>

jQuery toggle()
You can also toggle between hiding and showing an element with the
toggle() method.

Shown elements are hidden and hidden elements are shown:

<!DOCTYPE html>
<html>
<head>
<script
src="[Link]
[Link]"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").toggle();
});
});
</script>
</head>
<body>

<button>Toggle between hiding and showing the paragraphs</button>

<p>This is a paragraph with little content.</p>


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

</body>
</html>

jQuery fadeIn() Method


The jQuery fadeIn() method is used to fade in a hidden element.

Syntax:

$(selector).fadeIn(speed,callback);

The optional speed parameter specifies the duration of the effect. It can take
the following values: "slow", "fast", or milliseconds.

The optional callback parameter is a function to be executed after the fading


completes.

The following example demonstrates the fadeIn() method with different


parameters:

<!DOCTYPE html>
<html>
<head>
<script
src="[Link]
[Link]"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").fadeIn();
$("#div2").fadeIn("slow");
$("#div3").fadeIn(3000);
});
});
</script>
</head>
<body>

<p>Demonstrate fadeIn() with different parameters.</p>

<button>Click to fade in boxes</button><br><br>

<div id="div1"
style="width:80px;height:80px;display:none;background-
color:red;"></div><br>
<div id="div2"
style="width:80px;height:80px;display:none;background-
color:green;"></div><br>
<div id="div3"
style="width:80px;height:80px;display:none;background-
color:blue;"></div>

</body>
</html>

jQuery fadeOut() Method


The jQuery fadeOut() method is used to fade out a visible element.

Syntax:

$(selector).fadeOut(speed,callback);

The optional speed parameter specifies the duration of the effect. It can take
the following values: "slow", "fast", or milliseconds.

The optional callback parameter is a function to be executed after the fading


completes.

The following example demonstrates the fadeOut() method with different


parameters:

<!DOCTYPE html>
<html>
<head>
<script
src="[Link]
[Link]"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").fadeOut();
$("#div2").fadeOut("slow");
$("#div3").fadeOut(3000);
});
});
</script>
</head>
<body>
<p>Demonstrate fadeOut() with different parameters.</p>

<button>Click to fade out boxes</button><br><br>

<div id="div1" style="width:80px;height:80px;background-


color:red;"></div><br>
<div id="div2" style="width:80px;height:80px;background-
color:green;"></div><br>
<div id="div3" style="width:80px;height:80px;background-
color:blue;"></div>

</body>
</html>

jQuery Sliding Methods


With jQuery you can create a sliding effect on elements.

jQuery has the following slide methods:

● slideDown()
● slideUp()
● slideToggle()

jQuery slideDown() Method


The jQuery slideDown() method is used to slide down an element.

Syntax:

$(selector).slideDown(speed,callback);

The optional speed parameter specifies the duration of the effect. It can take
the following values: "slow", "fast", or milliseconds.

The optional callback parameter is a function to be executed after the sliding


completes.

The following example demonstrates the slideDown() method:

<!DOCTYPE html>
<html>
<head>
<script
src="[Link]
[Link]"></script>
<script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideDown("slow");
});
});
</script>
<style>
#panel, #flip {
padding: 5px;
text-align: center;
background-color: #e5eecc;
border: solid 1px #c3c3c3;
}

#panel {
padding: 50px;
display: none;
}
</style>
</head>
<body>

<div id="flip">Click to slide down panel</div>


<div id="panel">Hello world!</div>

</body>
</html>

jQuery Animations - The animate()


Method
The jQuery animate() method is used to create custom animations.

$(selector).animate({params},speed,callback);

he required params parameter defines the CSS properties to be animated.

The optional speed parameter specifies the duration of the effect. It can take
the following values: "slow", "fast", or milliseconds.

The optional callback parameter is a function to be executed after the


animation completes.
The following example demonstrates a simple use of the animate() method;
it moves a <div> element to the right, until it has reached a left property of
250px:

<!DOCTYPE html>
<html>
<head>
<script
src="[Link]
[Link]"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").animate({left: '250px'});
});
});
</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:100px;position:absol
ute;"></div>

</body>
</html>

jQuery stop() Method


The jQuery stop() method is used to stop an animation or effect before it is
finished.

The stop() method works for all jQuery effect functions, including sliding,
fading and custom animations.

Syntax:

$(selector).stop(stopAll,goToEnd);
The optional stopAll parameter specifies whether also the animation queue
should be cleared or not. Default is false, which means that only the active
animation will be stopped, allowing any queued animations to be performed
afterwards.

The optional goToEnd parameter specifies whether or not to complete the


current animation immediately. Default is false.

So, by default, the stop() method kills the current animation being
performed on the selected element.

The following example demonstrates the stop() method, with no


parameters:

<!DOCTYPE html>
<html>
<head>
<script
src="[Link]
[Link]"></script>
<script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideDown(5000);
});
$("#stop").click(function(){
$("#panel").stop();
});
});
</script>
<style>
#panel, #flip {
padding: 5px;
font-size: 18px;
text-align: center;
background-color: #555;
color: white;
border: solid 1px #666;
border-radius: 3px;
}

#panel {
padding: 50px;
display: none;
}
</style>
</head>
<body>

<button id="stop">Stop sliding</button>

<div id="flip">Click to slide down panel</div>


<div id="panel">Hello world!</div>

</body>
</html>

jQuery Callback Functions


JavaScript statements are executed line by line. However, with effects, the
next line of code can be run even though the effect is not finished. This can
create errors.

To prevent this, you can create a callback function.

A callback function is executed after the current effect is finished.

Typical syntax: $(selector).hide(speed,callback);

Examples

The example below has a callback parameter that is a function that will be
executed after the hide effect is completed:

<!DOCTYPE html>
<html>
<head>
<script
src="[Link]
[Link]"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").hide("slow", function(){
alert("The paragraph is now hidden");
});
});
});
</script>
</head>
<body>

<button>Hide</button>
<p>This is a paragraph with little content.</p>

</body>
</html>

<!DOCTYPE html>
<html>
<head>
<script
src="[Link]
[Link]"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").hide(1000);
alert("The paragraph is now hidden");
});
});
</script>
</head>
<body>

<button>Hide</button>

<p>This is a paragraph with little content.</p>

</body>
</html>

jQuery Method Chaining


Until now we have been writing jQuery statements one at a time (one after
the other).

However, there is a technique called chaining, that allows us to run multiple


jQuery commands, one after the other, on the same element(s).

Tip: This way, browsers do not have to find the same element(s) more than
once.

To chain an action, you simply append the action to the previous action.
The following example chains together the css(), slideUp(), and
slideDown() methods. The "p1" element first changes to red, then it slides
up, and then it slides down:

<!DOCTYPE html>
<html>
<head>
<script
src="[Link]
[Link]"></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>

Another example:

<!DOCTYPE html>
<html>
<head>
<script
src="[Link]
[Link]"></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>

jQuery - Get Content and Attributes


jQuery contains powerful methods for changing and manipulating HTML
elements and attributes.

jQuery DOM Manipulation


One very important part of jQuery is the possibility to manipulate the DOM.

jQuery comes with a bunch of DOM related methods that make it easy to
access and manipulate elements and attributes.

DOM = Document Object Model:

The DOM defines a standard for accessing HTML and XML documents:

Get Content - text(), html(), and val()


Three simple, but useful, jQuery methods for DOM manipulation are:

● text() - Sets or returns the text content of selected elements


● html() - Sets or returns the content of selected elements (including
HTML markup)
● val() - Sets or returns the value of form fields

The following example demonstrates how to get content with the jQuery
text() and html() methods:

<!DOCTYPE html>
<html>
<head>
<script
src="[Link]
[Link]"></script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
alert("Text: " + $("#test").text());
});
$("#btn2").click(function(){
alert("HTML: " + $("#test").html());
});
});
</script>
</head>
<body>

<p id="test">This is some <b>bold</b> text in a paragraph.</p>

<button id="btn1">Show Text</button>


<button id="btn2">Show HTML</button>

</body>
</html>

The following example demonstrates how to get the value of an input field
with the jQuery val() method:

<!DOCTYPE html>
<html>
<head>
<script
src="[Link]
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>

Get Attributes - attr()


The jQuery attr() method is used to get attribute values.

The following example demonstrates how to get the value of the href
attribute in a link:

<!DOCTYPE html>
<html>
<head>
<script
src="[Link]
script>
<script>
$(document).ready(function(){
$("button").click(function(){
alert($("#ws").attr("href"));
});
});
</script>
</head>
<body>

<p><a href="[Link] id="ws">[Link]</a></p>

<button>Show href Value</button>

</body>
</html>

jQuery - Set Content and Attributes

Set Content - text(), html(), and val()


We will use the same three methods from the previous page to set content:

● text() - Sets or returns the text content of selected elements


● html() - Sets or returns the content of selected elements (including
HTML markup)
● val() - Sets or returns the value of form fields

The following example demonstrates how to set content with the jQuery
text(), html(), and val() methods:

<!DOCTYPE html>
<html>
<head>
<script src="[Link]
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("#test1").text("Hello world!");
});
$("#btn2").click(function(){
$("#test2").html("<b>Hello world!</b>");
});
$("#btn3").click(function(){
$("#test3").val("Dolly Duck");
});
});
</script>
</head>
<body>

<p id="test1">This is a paragraph.</p>


<p id="test2">This is another paragraph.</p>

<p>Input field: <input type="text" id="test3" value="Mickey Mouse"></p>

<button id="btn1">Set Text</button>


<button id="btn2">Set HTML</button>
<button id="btn3">Set Value</button>

</body>
</html>

A Callback Function for text(), html(), and


val()
All of the three jQuery methods above: text(), html(), and val(), also
come with a callback function. The callback function has two parameters: the
index of the current element in the list of elements selected and the original
(old) value. You then return the string you wish to use as the new value from
the function.

The following example demonstrates text() and html() with a callback


function:

<!DOCTYPE html>
<html>
<head>
<script src="[Link]
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("#test1").text(function(i, origText){
return "Old text: " + origText + " New text: Hello world! (index: " + i + ")";
});
});

$("#btn2").click(function(){
$("#test2").html(function(i, origText){
return "Old html: " + origText + " New html: Hello <b>world!</b> (index: " + i + ")";
});
});
});
</script>
</head>
<body>

<p id="test1">This is a <b>bold</b> paragraph.</p>


<p id="test2">This is another <b>bold</b> paragraph.</p>

<button id="btn1">Show Old/New Text</button>


<button id="btn2">Show Old/New HTML</button>

</body>
</html>

Set Attributes - attr()


The jQuery attr() method is also used to set/change attribute values.

The following example demonstrates how to change (set) the value of the
href attribute in a link:

<!DOCTYPE html>
<html>
<head>
<script src="[Link]
<script>
$(document).ready(function(){
$("button").click(function(){
$("#ws").attr("href", "[Link]
});
});
</script>
</head>
<body>

<p><a href="[Link] id="ws">[Link]</a></p>

<button>Change href Value</button>

<p>Mouse over the link (or click on it) to see that the value of the href attribute has
changed.</p>

</body>
</html>

The attr() method also allows you to set multiple attributes at the same
time.

The following example demonstrates how to set both the href and title
attributes at the same time:

<!DOCTYPE html>
<html>
<head>
<script src="[Link]
<script>
$(document).ready(function(){
$("button").click(function(){
$("#ws").attr({
"href" : "[Link]
"title" : "xyztutorial"
});
});
});
</script>
</head>
<body>

<p><a href="[Link] title="some title" id="ws">[Link]</a></p>

<button>Change href and title</button>


<p>Mouse over the link to see that the href attribute has changed and a title attribute is
set.</p>

</body>
</html>

jQuery - Add Elements


With jQuery, it is easy to add new elements/content.

Add New HTML Content


We will look at four jQuery methods that are used to add new content:

● append() - Inserts content at the end of the selected elements


● prepend() - Inserts content at the beginning of the selected elements
● after() - Inserts content after the selected elements
● before() - Inserts content before the selected elements

jQuery append() Method


The jQuery append() method inserts content AT THE END of the selected
HTML elements.

<!DOCTYPE html>
<html>
<head>
<script
src="[Link]
script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("p").append(" <b>Appended text</b>.");
});

$("#btn2").click(function(){
$("ol").append("<li>Appended item</li>");
});
});
</script>
</head>
<body>

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

<ol>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ol>

<button id="btn1">Append text</button>


<button id="btn2">Append list items</button>

</body>
</html>

jQuery prepend() Method


The jQuery prepend() method inserts content AT THE BEGINNING of the
selected HTML elements.

<!DOCTYPE html>
<html>
<head>
<script
src="[Link]
script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("p").prepend("<b>Prepended text</b>. ");
});
$("#btn2").click(function(){
$("ol").prepend("<li>Prepended item</li>");
});
});
</script>
</head>
<body>

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

<ol>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ol>

<button id="btn1">Prepend text</button>


<button id="btn2">Prepend list item</button>

</body>
</html>

Add Several New Elements With append()


and prepend()
In both examples above, we have only inserted some text/HTML at the
beginning/end of the selected HTML elements.

However, both the append() and prepend() methods can take an infinite
number of new elements as parameters. The new elements can be generated
with text/HTML (like we have done in the examples above), with jQuery, or
with JavaScript code and DOM elements.

In the following example, we create several new elements. The elements are
created with text/HTML, jQuery, and JavaScript/DOM. Then we append the
new elements to the text with the append() method (this would have worked
for prepend() too) :

<!DOCTYPE html>
<html>
<head>
<script
src="[Link]
script>
<script>
function appendText() {
var txt1 = "<p>Text.</p>"; // Create text with HTML
var txt2 = $("<p></p>").text("Text."); // Create text with jQuery
var txt3 = [Link]("p");
[Link] = "Text."; // Create text with DOM
$("body").append(txt1, txt2, txt3); // Append new elements
}
</script>
</head>
<body>

<p>This is a paragraph.</p>
<button onclick="appendText()">Append text</button>

</body>
</html>

jQuery after() and before() Methods


The jQuery after() method inserts content AFTER the selected HTML
elements.

The jQuery before() method inserts content BEFORE the selected HTML
elements.

<!DOCTYPE html>
<html>
<head>
<script
src="[Link]
script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("img").before("<b>Before</b>");
});

$("#btn2").click(function(){
$("img").after("<i>After</i>");
});
});
</script>
</head>
<body>

<img src="/images/[Link]" alt="jQuery" width="100"


height="140"><br><br>

<button id="btn1">Insert before</button>


<button id="btn2">Insert after</button>
</body>
</html>

Add Several New Elements With after()


and before()
Also, both the after() and before() methods can take an infinite number
of new elements as parameters. The new elements can be generated with
text/HTML (like we have done in the example above), with jQuery, or with
JavaScript code and DOM elements.

In the following example, we create several new elements. The elements are
created with text/HTML, jQuery, and JavaScript/DOM. Then we insert the new
elements to the text with the after() method (this would have worked for
before() too) :

<!DOCTYPE html>
<html>
<head>
<script
src="[Link]
script>
<script>
function afterText() {
var txt1 = "<b>I </b>"; // Create element with HTML
var txt2 = $("<i></i>").text("love "); // Create with jQuery
var txt3 = [Link]("b"); // Create with DOM
[Link] = "jQuery!";
$("img").after(txt1, txt2, txt3); // Insert new elements after img
}
</script>
</head>
<body>

<img src="/images/[Link]" alt="jQuery" width="100" height="140">

<p>Click the button to insert text after the image.</p>

<button onclick="afterText()">Insert after</button>

</body>
</html>

jQuery - Remove Elements


With jQuery, it is easy to remove existing HTML elements.

Remove Elements/Content
To remove elements and content, there are mainly two jQuery methods:

● remove() - Removes the selected element (and its child elements)


● empty() - Removes the child elements from the selected element

jQuery remove() Method


The jQuery remove() method removes the selected element(s) and its child
elements.

////******To check

<!DOCTYPE html>
<html>
<head>
<script
src=”[Link]
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").remove();
});
});
</script>
</head>
<body>

<div id="div1" style="height:100px;width:300px;border:1px solid


black;background-color:yellow;">

This is some text in the div.


<p>This is a paragraph in the div.</p>
<p>This is another paragraph in the div.</p>

</div>
<br>
<button>Remove div element</button>

</body>
</html>

jQuery empty() Method


The jQuery empty() method removes the child elements of the selected
element(s).

<!DOCTYPE html>
<html>
<head>
<script
src="[Link]
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").empty();
});
});
</script>
</head>
<body>

<div id="div1" style="height:100px;width:300px;border:1px solid


black;background-color:yellow;">

This is some text in the div.


<p>This is a paragraph in the div.</p>
<p>This is another paragraph in the div.</p>

</div>
<br>

<button>Empty the div element</button>

</body>
</html>

Filter the Elements to be Removed


The jQuery remove() method also accepts one parameter, which allows you
to filter the elements to be removed.
The parameter can be any of the jQuery selector syntaxes.

The following example removes all <p> elements with class="test":

<!DOCTYPE html>
<html>
<head>
<script
src="[Link]
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").remove(".test");
});
});
</script>
<style>
.test {
color: red;
font-size: 20px;
}
</style>
</head>
<body>

<p>This is a paragraph.</p>
<p class="test">This is another paragraph.</p>
<p class="test">This is another paragraph.</p>

<button>Remove all p elements with class="test"</button>

</body>
</html

>

jQuery - AJAX Introduction


AJAX is the art of exchanging data with a server, and updating parts of a
web page - without reloading the whole page.

What is AJAX?
AJAX = Asynchronous JavaScript and XML.

In short; AJAX is about loading data in the background and display it on the
webpage, without reloading the whole page.

Examples of applications using AJAX: Gmail, Google Maps, Youtube, and


Facebook tabs.

What About jQuery and AJAX?


jQuery provides several methods for AJAX functionality.

With the jQuery AJAX methods, you can request text, HTML, XML, or JSON
from a remote server using both HTTP Get and HTTP Post - And you can load
the external data directly into the selected HTML elements of your web page!

jQuery - AJAX load() Method


jQuery load() Method
The jQuery load() method is a simple, but powerful AJAX method.

The load() method loads data from a server and puts the returned data into
the selected element.

Syntax:

$(selector).load(URL,data,callback);

The required URL parameter specifies the URL you wish to load.

The optional data parameter specifies a set of querystring key/value pairs to


send along with the request.

The optional callback parameter is the name of a function to be executed


after the load() method is completed.

Here is the content of our example file: "demo_test.txt":

<h2>jQuery and AJAX is FUN!!!</h2>


<p id="p1">This is some text in a paragraph.</p>
The following example loads the content of the file "demo_test.txt" into a
specific <div> element:

<!DOCTYPE html>
<html>
<head>
<script
src="[Link]
script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").load("demo_test.txt");
});
});
</script>
</head>
<body>

<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>

<button>Get External Content</button>

</body>
</html>

It is also possible to add a jQuery selector to the URL parameter.

The following example loads the content of the element with id="p1", inside
the file "demo_test.txt", into a specific <div> element:

The optional callback parameter specifies a callback function to run when the
load() method is completed. The callback function can have different
parameters:

● responseTxt - contains the resulting content if the call succeeds


● statusTxt - contains the status of the call
● xhr - contains the XMLHttpRequest object

The following example displays an alert box after the load() method
completes. If the load() method has succeeded, it displays "External
content loaded successfully!", and if it fails it displays an error message:

<!DOCTYPE html>
<html>
<head>
<script
src="[Link]
script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").load("demo_test.txt", function(responseTxt, statusTxt, xhr){
if(statusTxt == "success")
alert("External content loaded successfully!");
if(statusTxt == "error")
alert("Error: " + [Link] + ": " + [Link]);
});
});
});
</script>
</head>
<body>

<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>

<button>Get External Content</button>

</body>
</html>

jQuery - AJAX get() and post() Methods

The jQuery get() and post() methods are used to request data from the
server with an HTTP GET or POST request.

HTTP Request: GET vs. POST


Two commonly used methods for a request-response between a client and
server are: GET and POST.

● GET - Requests data from a specified resource


● POST - Submits data to be processed to a specified resource
GET is basically used for just getting (retrieving) some data from the server.
Note: The GET method may return cached data.

POST can also be used to get some data from the server. However, the POST
method NEVER caches data, and is often used to send data along with the
request.

jQuery $.get() Method


The $.get() method requests data from the server with an HTTP GET
request.

The required URL parameter specifies the URL you wish to request.

The optional callback parameter is the name of a function to be executed if


the request succeeds.

The following example uses the $.get() method to retrieve data from a file
on the server:

<!DOCTYPE html>
<html>
<head>
<script
src="[Link]
script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.get("demo_test.asp", function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});
</script>
</head>
<body>

<button>Send an HTTP GET request to a page and get the result


back</button>

</body>
</html>
jQuery $.post() Method
The $.post() method requests data from the server using an HTTP POST
request.

<!DOCTYPE html>
<html>
<head>
<script
src="[Link]
script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.post("demo_test_post.asp",
{
name: "Donald Duck",
city: "Duckburg"
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});
</script>
</head>
<body>

<button>Send an HTTP POST request to a page and get the result


back</button>

</body>
</html>

The first parameter of $.post() is the URL we wish to request


("demo_test_post.asp").

Then we pass in some data to send along with the request (name and city).

The ASP script in "demo_test_post.asp" reads the parameters, processes


them, and returns a result.
The third parameter is a callback function. The first callback parameter holds
the content of the page requested, and the second callback parameter holds
the status of the request.

Tip: Here is how the ASP file looks like ("demo_test_post.asp"):

<%
dim fname,city
fname=[Link]("name")
city=[Link]("city")
[Link]("Dear " & fname & ". ")
[Link]("Hope you live well in " & city & ".")
%>

jQuery Filters
Use jQuery to filter/search for specific elements.

Filter Tables
Perform a case-insensitive search for items in a table:

<!DOCTYPE html>
<html>
<head>
<script
src="[Link]
[Link]"></script>
<script>
$(document).ready(function(){
$("#myInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#myTable tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value)
> -1)
});
});
});
</script>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}

td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}

tr:nth-child(even) {
background-color: #dddddd;
}
</style>
</head>
<body>

<h2>Filterable Table</h2>
<p>Type something in the input field to search the table for
first names, last names or emails:</p>
<input id="myInput" type="text" placeholder="Search..">
<br><br>

<table>
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
</thead>
<tbody id="myTable">
<tr>
<td>John</td>
<td>Doe</td>
<td>john@[Link]</td>
</tr>
<tr>
<td>Mary</td>
<td>Moe</td>
<td>mary@[Link]</td>
</tr>
<tr>
<td>July</td>
<td>Dooley</td>
<td>july@[Link]</td>
</tr>
<tr>
<td>Anja</td>
<td>Ravendale</td>
<td>a_r@[Link]</td>
</tr>
</tbody>
</table>

<p>Note that we start the search in tbody, to prevent filtering


the table headers.</p>

</body>
</html>

Filter Lists
Perform a case-insensitive search for items in a list:

<!DOCTYPE html>
<html>
<head>
<script
src="[Link]
[Link]"></script>
<script>
$(document).ready(function(){
$("#myInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#myList li").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value)
> -1)
});
});
});
</script>
</head>
<body>

<h2>Filterable List</h2>
<p>Type something in the input field to search the list for
specific items:</p>
<input id="myInput" type="text" placeholder="Search..">
<br>
<ul id="myList">
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
<li>Fourth</li>
</ul>

</body>
</html>

Filter Anything
Perform a case-insensitive search for text inside a div element:

<!DOCTYPE html>
<html>
<head>
<script
src="[Link]
[Link]"></script>
<script>
$(document).ready(function(){
$("#myInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#myDIV *").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value)
> -1)
});
});
});
</script>
</head>
<body>

<h2>Filter Anything</h2>
<p>Type something in the input field to search for a specific
text inside the div element with id="myDIV":</p>
<input id="myInput" type="text" placeholder="Search..">

<div id="myDIV">
<p>I am a paragraph.</p>
<div>I am a div element inside div.</div>
<button>I am a button</button>
<button>Another button</button>
<p>Another paragraph.</p>
</div>

</body>
</html>

You might also like