1. IT2304 – Full Stack Web Development Unit I - JQUERY
Prepared by Dr. R. Arthy, AP/IT 1
Department of Information Technology
2023 – 2024 (ODD SEMESTER)
Year : III IT Course Code : IT2304
Faculty Name : Dr. R. Arthy, AP/IT Course Name : Full Stack Web Development
Course code
(as per NBA)
: 21ITC304 Regulation : R2021
UNIT I – JQUERY
CHEAT SHEAT
Topic 1: Selecting Elements using jQuery
Syntax:
$(selector expression, context)
OR
jQuery(selector expression, context)
S. No. Category Selector Description Example
1. Element Selector
$(„element‟)
$(“element1, element2, element”)
Find all the mentioned elements
$(“p”) – Find all the “p” element
$(“div, p, span”) – Find all the div, p, and
span element
2. Descendent $(“parentElement childElement”) Find the descendent elements $(“div pre”) – Find all the pre elements
2. IT2304 – Full Stack Web Development Unit I - JQUERY
Prepared by Dr. R. Arthy, AP/IT 2
Selector $(“parentElement > childElement”) which are descendent of div
3.
Universal
Selector
$(*) Universal selector $(*) – Find all the elements
4. ID Selector
$(“#id”)
$(“div#id”)
$(“#id1, #id2, #idN”)
ID selector – Selects the
elements with mentioned id
$(“#sample”) – Find element whose id is
“sample”
$(div#sample”) – Find div element whose
id if “sample”
$(“#sample, #simple, #robust”) – Find
the elements with mentioned ids
5. Class Selector
$(“.class1”)
$(“div.class1”)
$(“.class1, .class2, .classN”)
Class selector – Selects the
elements with mentioned class
name
$(“.csample”) – Find element whose class
name is “sample”
$(div.csample”) – Find div element
whose class name is “sample”
$(“.csample1, .csimple2, .crobust”) –
Find the elements with mentioned class
names
6.
Child Selector
$(“element:first_child”)
Selects all the elements, which is
the first child of its parent
element.
$(“div:first_child”)
7. $(“element:last_child”)
Selects all the elements which
are the last child of its parent
element.
$(“div:last_child”)
8. $("elemnt:nth-child(5)")
Selects all the elements which
are the 5th child of its parent
element.
$(“p:nth-child(5)”)
9. $("elememt:nth-last-child(2)")
Selects all elements which are
the 2nd last child of its parent
element.
$(“p:nth-last-child(5)”)
10. $("element:only-child")
Selects all the elements which is
the only child of its parent
element.
$("p:only-child")
3. IT2304 – Full Stack Web Development Unit I - JQUERY
Prepared by Dr. R. Arthy, AP/IT 3
11.
Attribute Selector
$(“[attribute]”)
Selects all the elements with the
mentioned attribute
$(“[class]”) – Find all the elements with
the class attribute
12. $(“element[attribute]”)
Selects all the elements that have
a mentioned attribute
$('div[class]') – Find all the <div>
elements that have a class attribute
13. $(“element[attribute=value]')
Find all the elements whose
attributes are equal to value.
$(“div[id=sample]')
14. $('div[class *="myCls"]')
Selects <div> elements whose
class attributes contain myCls.
-
15. $('div[class~=myCls]')
Selects div elements whose class
attributes contain myCls,
delimited by spaces.
-
16. $("div[class $= 'myCls']")
Selects <div> elements whose
class attribute value ends with
myCls. The comparison is case
sensitive.
-
17. $("div[class != 'myCls']")
Selects <div> elements which do
not have class attribute or value
does not equal to myCls.
-
18. $("div[class ^= 'myCls']")
Selects <div> elements whose
class attribute value starts with
myCls.
-
19.
$("div:contains('tutorialsteacher')"
Selects all <div> elements that
contains the text
'tutorialsteacher'
-
20.
Input Type
Selector
$(":input") Selects all input elements. -
21. $(":button")
Selects all input elements where
type="button".
-
22. $(":radio")
Selects all input types where
type="radio"
-
4. IT2304 – Full Stack Web Development Unit I - JQUERY
Prepared by Dr. R. Arthy, AP/IT 4
23. $(":text")
Selects all input elements where
type="text"
-
24.
$(":checkbox")
Selects all checkbox elements. -
25. $(":submit")
Selects all input elements where
type="submit"
-
26. $(":password")
Selects all input elements where
type="password".
-
27. $(":reset")
Selects all input elements where
type="reset".
-
28. $(':image')
Selects all input elements where
type="image".
-
29. $(':file')
Selects all input elements where
type="file".
-
30. $(':enabled')
Selects all enabled input
elements.
-
31. $(':disabled')
Selects all disabled input
elements.
-
32. $(':selected')
Selects all selected input
elements.
-
33. $(':checked')
Selects all checked input
elements.
-
34. $(':hidden')
Selects all hidden elements.
:visible
-
35. $(':visible') Selects all visible elements. -
36.
Table Selector
$('tr:odd') Selects all odd rows. (1,3,5,7..) -
37. $'tr:even') Selects all even rows.(0,2,4,6..) -
5. IT2304 – Full Stack Web Development Unit I - JQUERY
Prepared by Dr. R. Arthy, AP/IT 5
Topic 2: Effects
S. No. Method Syntax Description Example
Hide / Show
1. .hide() $(selector).hide(speed, callback) Hide selected element(s) $('#div1').hide(5000);
2. .show() $(selector).show(speed, callback) Display selected element(s). $('#div1').show(5000);
3. .toggle() $(selector).toggle(speed, callback)
Display hidden element(s) or hide visible
element(s).
$('#div1').toggle(5000);
Fading
4. .fadeIn() $(selector).fadeIn(speed, callback)
Display selected element(s) by fading
them to opaque.
$('#div1').fadeIn(5000);
5. .fadeOut() $(selector).fadeOut(speed, callback)
Hides selected element(s) by fading them
to transparent.
$('#div1').fadeOut(5000);
6. .fadeTo() $(selector).fadeTo(speed, opacity, callback)
Adjust the opacity of the selected
element(s)
$('#div1').fadeTo(5000, 0.4);
7. .fadeToggle() $(selector).fadeToggle(speed, callback)
Display or hide the selected element(s)
by animating their opacity.
$('#div1').fadeToggle(5000);
Sliding
8. .slideUp() $(selector).slideUp(speed, callback)
Hide selected element(s) with sliding up
motion.
$('#div1').slideUp(5000);
9. .slideDown() $(selector).slideDown(speed, callback)
Display selected element(s) with sliding
down motion.
$('#div1').slideDown(5000);
10. .slideToggle() $(selector).slideToggle(speed, callback)
Display or hide selected element(s) with
sliding motion.
$('#div1').slideToggle(5000);
Animation
6. IT2304 – Full Stack Web Development Unit I - JQUERY
Prepared by Dr. R. Arthy, AP/IT 6
11. .animate() $(selector).animate({params},speed,callback);
Perform custom animation using
element's style properties.
$('#div1').animate({ height:
'200px', width: '200px'});
12. .clearQueue() $(selector).clearQueue(queueName)
Remove all the animations from the
queue that have not been run.
$('#div1').clearQueue();
13. .delay() $(selector).delay(speed,queueName)
Set a timer to delay execution of
animations in the queue.
$('#div1).delay(5000);
14. .dequeue() $(selector).dequeue(queueName)
Execute the next animation in the queue
for the selected element.
$('#div1').dequeue();
15. .queue() $(selector).queue(queueName)
Show or manipulate the queue of
functions to be executed on the selected
element.
$('#div1').queue().length;
16. .finish() $(selector).finish(queueName)
Stop currently running animation and
clear the queue for selected element(s)
$('#div1').finish();
17. .stop() $(selector).stop(stopAll,goToEnd)
Stop currently running animations on the
selected element(s).
$('#div1').stop();
Topic 3: Events
S. No. Methods Syntax Description Example
Form Events
1. .blur() $(selector).blur(function)
The blur event occurs when an
element loses focus.
$("input").blur(function(){
alert("Blur Method.");
});
2. .change() $(selector).change(function)
The change event occurs when the
value of an element has been
changed (only works on <input>,
<textarea> and <select> elements).
$("input").change(function(){
alert("Text Changed");
});
3. .focus() $(selector).focus(function)
The focus event occurs when an
element gets focus (when selected by
$("input").focus(function(){
$("span").css("display", "inline");
7. IT2304 – Full Stack Web Development Unit I - JQUERY
Prepared by Dr. R. Arthy, AP/IT 7
a mouse click or by "tab-navigating"
to it).
});
4. .focusIn() $(selector).focusin(function)
The focusin event occurs when an
element (or any elements inside it)
gets focus.
$("div").focusin(function(){
$(this).css("background-color",
"#FFFFCC");
});
5. .focusOut() $(selector).focusout(function)
The focusout event occurs when an
element (or any elements inside it)
loses focus.
$("div").focusout(function(){
$(this).css("background-color",
"#FFFFCC");
});
6. .select() $(selector).select(function)
The select event occurs when a text
is selected (marked) in a text area or
a text field.
$("input").select(function(){
alert("Text marked!");
});
7. .submit() $(selector).submit(function)
The submit event occurs when a
form is submitted.
$("form").submit(function(){
alert("Submitted");
});
Keyboard Events
8. .keydown() $(selector).keydown(function)
The keydown event occurs when a
keyboard key is pressed down.
$("input").keydown(function(){
$("input").css("background-color",
"yellow");
});
9. .keypress() $(selector).keypress(function)
The keypress() method triggers the
keypress event, or attaches a function
to run when a keypress event occurs.
$("input").keypress(function(){
$("span").text(i += 1);
});
10. .keyup() $(selector).keyup(function)
The keyup event occurs when a
keyboard key is released.
$("input").keyup(function(){
$("input").css("background-color",
"pink");
});
Mouse Events
11. .click() $(selector).click(function) The click event occurs when an $("p").click(function(){
8. IT2304 – Full Stack Web Development Unit I - JQUERY
Prepared by Dr. R. Arthy, AP/IT 8
element is clicked. alert("The paragraph was clicked.");
});
12. .dblclick() $(selector).dblclick(function)
The dblclick event occurs when an
element is double-clicked.
$("p").dblclick(function(){
alert("The paragraph was clicked.");
});
13. .hover()
$(selector).hover(inFunction,
outFunction)
The hover() method specifies two
functions to run when the mouse
pointer hovers over the selected
elements.
$("p").hover(function(){
$(this).css("background-color",
"yellow");
}, function(){
$(this).css("background-color", "pink");
});
14. .mousedown() $(selector).mousedown(function)
The mousedown event occurs when
the left mouse button is pressed
down over the selected element.
$("div").mousedown(function(){
$(this).after("Mouse button pressed
down.");
});
15. .mouseup() $(selector).mouseup(function)
The mouseup event occurs when the
left mouse button is released over the
selected element.
$("div").mouseup(function(){
$(this).after("Mouse button released.");
});
16. .mouseenter() $(selector).mouseenter(function)
The mouseenter event occurs when
the mouse pointer is over (enters) the
selected elemen
$("p").mouseenter(function(){
$("p").css("background-color",
"yellow");
});
17. .mouseleave() $(selector).mouseleave(function)
The mouseleave event occurs when
the mouse pointer leaves the selected
element.
$("p").mouseleave(function(){
$("p").css("background-color", "gray");
});
18. .mousemove() $(selector).mousemove(function)
The mousemove event occurs
whenever the mouse pointer moves
within the selected element.
$(document).mousemove(function(event){
$("span").text(event.pageX + ", " +
event.pageY);
});
19. .mouseout() $(selector).mouseout(function)
The mouseout event occurs when the
mouse pointer leaves the selected
element.
$("p").mouseout(function(){
$("p").css("background-color", "gray");
});
9. IT2304 – Full Stack Web Development Unit I - JQUERY
Prepared by Dr. R. Arthy, AP/IT 9
Unlike the mouseleave event, the
mouseout event is triggered if a
mouse pointer leaves any child
elements as well as the selected
element. The mouseleave event only
triggers when the mouse pointer
leaves the selected element.
20. .mouseover() $(selector).mouseover(function)
The mouseover event occurs when
the mouse pointer is over the
selected element.
Unlike the mouseenter event, the
mouseover event triggers if a mouse
pointer enters any child elements as
well as the selected element. The
mouseenter event is only triggered
when the mouse pointer enters the
selected element.
$("p").mouseover(function(){
$("p").css("background-color",
"yellow");
});
Browser Events
21. .resize() $(selector).resize(function)
The resize event occurs when the
browser window changes size.
$(window).resize(function(){
$('span').text(x += 1);
});
22. .scroll() $(selector).scroll(function)
The scroll event occurs when the
user scrolls in the specified element.
$("div").scroll(function(){
$("span").text(x += 1);
});
Document Events
23. .ready() $(document).ready(function)
The ready event occurs when the
DOM (document object model) has
been loaded.
$(document).ready(function(){
$("button").click(function(){
$("p").slideToggle();
});
});
10. IT2304 – Full Stack Web Development Unit I - JQUERY
Prepared by Dr. R. Arthy, AP/IT 10
Common Events
24. .on()
$(selector).on(event,
childSelector, data, function,
map)
The on() method attaches one or
more event handlers for the selected
elements and child elements.
$("p").on("click", function(){
alert("The paragraph was clicked.");
});
25. .off()
$(selector).off(event, selector,
function(eventObj), map)
The off() method is most often used
to remove event handlers attached
with the on() method.
$("button").click(function(){
$("p").off("click");
});
Topic 4: Utilities
S. No. Method Syntax Description Example
Utilities
1. .trim() $.trim(string)
Remove the whitespace from the
beginning and end of a string.
var inputValue = $('#inputField').val();
var trimmedValue =
$.trim(inputValue);
$('#output').text("Trimmed value: '" +
trimmedValue + "'");
2. .each() $.each(array, callback)
Iterate over specified elements and
execute specified call back function for
each element.
Example 1:
var output = $('#fruits');
var fruits = $('#fruitsList li');
fruits.each(function(index, element) {
output.append("Index " + index + ": " +
$(element).text() + "<br>"); });
Example 2:
$.each([ "JQuery", "AngularJS",
"NodeJS" ], function( idx, val ) {
console.log( "element " + idx + " is " +
11. IT2304 – Full Stack Web Development Unit I - JQUERY
Prepared by Dr. R. Arthy, AP/IT 11
val ); });
Example 3:
$.each({ FSD1: "JQuery", FSD2:
"AngularJS" }, function( k, v ) {
console.log( k + " : " + v ); });
3. .inArray()
$.inArray( value, array [,
fromIndex ] )
Search for a specified value within an
array and return its index (or -1 if not
found).
var valuesArray = ["Red", "Blue",
"Green", "Violet"];
var output = $('#check');
var valueToCheck = prompt("Enter a
value to check:");
var index = $.inArray(valueToCheck,
valuesArray);
if (index !== -1) {
output.text("Value '" + valueToCheck
+ "' found at index " + index);
} else {
output.text("Value '" + valueToCheck + "'
not found in the array.");
}
4. .extend()
$.extend( target, object1 [,
objectN ] )
Merge the contents of two or more
objects together into the first object.
Changes the properties of the first
object using the properties of
subsequent objects
If you don't want to change any of the
objects you pass to $.extend(), pass an
empty object as the first argument
Example 1:
var object1 = { a: 1, b: 2 };
var object2 = { b: 3, c: 4 };
var newObject = $.extend(object1,
object2);
$('#extend1').text(JSON.stringify(object1,
null, 2));
Example 2:
var object1 = { a: 1, b: 2 };
var object2 = { b: 3, c: 4 };
12. IT2304 – Full Stack Web Development Unit I - JQUERY
Prepared by Dr. R. Arthy, AP/IT 12
var newObject = $.extend(object1,
object2);
$('#extend1').text({},
JSON.stringify(object1, null, 2));
5. .isNumeric() $.isNumeric( value )
Determines whether its argument
represents a JavaScript number.
var inputValue = $('#inputValue').val();
var isNumeric =
$.isNumeric(inputValue);
if (isNumeric) {
alert("'" + inputValue + "' is
numeric.");
} else {
alert("'" + inputValue + "' is not
numeric.");
}
6. .map() $.map( array, callback )
Translate all items in an array or object
to new array of items.
var numbers = [1, 2, 3, 4, 5];
var squaredNumbers = $.map(numbers,
function(number) {
return number * number;
});
$('#map1').text("Squared numbers: " +
squaredNumbers.join(', '));
7. .grep()
$.grep( array, function [, invert ]
)
Finds the elements of an array which
satisfy a filter function. The original
array is not affected.
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9,
10];
var evenNumbers = $.grep(numbers,
function(number) {
return number % 2 === 0;
});
$('#even1').text("Even numbers: " +
evenNumbers.join(', '));
8. .merge() $.merge( first, second )
Merge the contents of two arrays
together into the first array.
var array1 = ["Jan", "Feb", "Mar"];
var array2 = ["Apr", "May", "June"];
var mergedArray = $.merge(array1,
13. IT2304 – Full Stack Web Development Unit I - JQUERY
Prepared by Dr. R. Arthy, AP/IT 13
array2);
$('#merge').html("<li>"+
mergedArray.join('</li><li>')+ "</li>");
DOM Manipulation
9. .append() $(„selector').append('content')
Inserts content to the end of element(s)
which is specified by a selector.
$('p').append('World!');
10. .before() $(„selector').before('content')
Inserts content (new or existing DOM
elements) before an element(s) which is
specified by a selector.
$('#div1').before('<div
style="background-color:yellow"> New
div </div>');
11. .after() $(„selector').after('content')
Inserts content (new or existing DOM
elements) after an element(s) which is
specified by a selector.
$('#div1').after('<div style="background-
color:yellow"> New div </div>');
12. .prepend() $(„selector').prepend('content')
Insert content at the beginning of an
element(s) specified by a selector.
$('div').prepend('<p>This is prepended
paragraph</p>');
13. .remove() $(„selector').remove()
Removes element(s) from DOM which
is specified by selector.
$('label').remove();
14. .wrap() $(„selector').wrap('content')
Wrap an HTML structure around each
element which is specified by selector.
$('span').wrap('<p></p>');
Attribute Manipulation
15. .attr()
Get - $('selector').attr('name')
Set -
$('selector').attr('name','value')
Get or set the value of specified
attribute of the target element(s).
$('p').attr('style');
$('div').attr('class','yellowDiv');
16. .prop()
Get - $('selector').prop('name')
Set -
$('selector').prop('name','value')
Get or set the value of specified
property of the target element(s).
var style = $('p').prop('style');
alert(style.fontWeight);
$('div').prop('class','yellowDiv');
17. .html() $('selector').html('content')
Get or set html content to the specified
target element(s).
$('#emptyDiv').html('<p>This is
paragraph.</p>');
18. .text()
Get - $('selector').text()
Set - $('selector').text('content')
Get or set text for the specified target
element(s).
$('p').text();
$('#emptyDiv').text('This is some text.');
14. IT2304 – Full Stack Web Development Unit I - JQUERY
Prepared by Dr. R. Arthy, AP/IT 14
19. .val()
Get - $('selector').val()
Set - $('selector').val('value')
Get or set value property of the
specified target element.
$('input:text').val();
$('input:text').val('Steve');
Traversing
20. .children() $('selector').children()
Get all the child elements of the
specified element(s)
alert($("span ul").children().text());
21. .find()
$('selector').find('selector
expression to find child
elements')
Get all the specified child elements of
each specified element(s).
alert($("ul").find(".selected").text());
22. .first() $('selector').first()
Get the first occurrence of the specified
element.
$("div ul li").first().css("color","red");
23. .next() $('selector').next()
Get the immediately following sibling
of the specified element.
$(".selected").next().css("background-
color","yellow");
24. .parent() $('selector').parent()
Get the parent of the specified
element(s).
alert('Parent element of #inrDiv: ' +
$('#inrDiv').parent().html());
25. .siblings() $('selector').siblings()
Get the siblings of each specified
element(s)
$("div p").siblings("h2").css("text-
align","right");
CSS Manipulation
26. .css()
$('selector').css('property','value')
$('selector expression').css(
{ 'property':'value', })
Get or set style properties to the
specified element(s).
$('#myDiv').css('background-
color','yellow');
$('p').css({'background-color':
'red','width':'400px'});
27. .addClass()
$('selector').addClass('css class
name')
Add one or more class to the specified
element(s).
$('#myDiv').addClass('yellowDiv');
28. .removeClass()
$('selector').removeClass('css
class name')
Remove a single class, multiple classes,
or all classes from the specified
element(s).
$('#myDiv').removeClass('yellowDiv');
29. .toggleClass()
$('selector').toggleClass('css
class name')
Toggles between adding/removing
classes to the specified elements
$('#myDiv').toggleClass('redDiv');
15. IT2304 – Full Stack Web Development Unit I - JQUERY
Prepared by Dr. R. Arthy, AP/IT 15
Topic 5: AJAX
S. No. Method Name Syntax Description Example
1. .ajax()
$.ajax({name:value, name:value, ... })
Properties:
Name Value/Description
async A Boolean value indicating
whether the request should be
handled asynchronous or not.
Default is true
beforeSend(xhr) A function to run before the
request is sent
cache A Boolean value indicating
whether the browser should
cache the requested pages.
Default is true
complete(xhr,
status)
A function to run when the
request is finished (after
success and error functions)
contentType The content type used when
sending data to the server.
Default is: "application/x-
www-form-urlencoded"
context Specifies the "this" value for
all AJAX related callback
functions
data Specifies data to be sent to
the server
dataType The data type expected of the
server response.
error(xhr, A function to run if the
To perform an AJAX
(asynchronous HTTP)
request.
$("button").click(function(){
$.ajax({url: "demo_test.txt", success:
function(result){
$("#div1").html(result);
}});
16. IT2304 – Full Stack Web Development Unit I - JQUERY
Prepared by Dr. R. Arthy, AP/IT 16
status, error) request fails.
password Specifies a password to be
used in an HTTP access
authentication request.
success(result,
status, xhr)
A function to be run when
the request succeeds
Timeout The local timeout (in
milliseconds) for the request
type Specifies the type of request.
(GET or POST)
url Specifies the URL to send
the request to. Default is the
current page
username Specifies a username to be
used in an HTTP access
authentication request
xhr A function used for creating
the XMLHttpRequest object
2. .get()
$.get(URL, data, function(data,status,xhr),
dataType)
To load data from the
server using a HTTP
GET request.
$("button").click(function(){
$.get("demo_test.asp", function(data,
status){
alert("Data: " + data + "nStatus: " +
status);
});
});
3. .post()
$.post(URL, data, function(data,status,xhr),
dataType)
To load data from the
server using a HTTP
$("button").click(function(){
$.post("demo_test.asp", function(data,
17. IT2304 – Full Stack Web Development Unit I - JQUERY
Prepared by Dr. R. Arthy, AP/IT 17
POST request. status){
alert("Data: " + data + "nStatus: " +
status);
});
});
4. .getJSON()
$(selector).getJSON(url, data,
success(data,status,xhr))
To get JSON data using
an AJAX HTTP GET
request.
$("button").click(function(){
$.getJSON("demo_ajax_json.js",
function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
});
});
5. .parseJSON() $(selector).parseJSON(json object)
Takes a well-formed
JSON string and returns
the resulting JavaScript
value
var jsonString = '{"name": "John", "age":
30, "city": "New York"}';
var jsonObject =
$.parseJSON(jsonString);
$('#parse').text(JSON.stringify(jsonObject,
null, 2));
6. .getScript() $(selector).getScript(url, success(response,status))
To get and execute a
JavaScript using an
AJAX HTTP GET
request.
$("button").click(function(){
$.getScript("demo_ajax_script.js");
});
7. .param() $.param(object,trad)
Creates a serialized
representation of an
array or an object.
$("button").click(function(){
$("div").text($.param(personObj));
});
8. .load()
$(selector).load(url,data,
function(response,status,xhr))
Loads data from a
server and puts the
returned data into the
selected element.
$("button").click(function(){
$("#div1").load("demo_test.txt");
});
9. .ajaxComplete()
$(document).ajaxComplete(
function(event,xhr,options))
A function to run when
an AJAX request
completes.
$(document).ajaxComplete(function(){
$("#wait").css("display", "none");
});
18. IT2304 – Full Stack Web Development Unit I - JQUERY
Prepared by Dr. R. Arthy, AP/IT 18
10. .ajaxStart() $(document).ajaxStart(function())
A function to run when
an AJAX request starts.
$(document).ajaxStart(function(){
$(this).html("<img
src='demo_wait.gif'>");
});
11. .ajaxStop() $(document).ajaxStop(function())
A function to run when
ALL AJAX requests
have completed.
$(document).ajaxStop(function(){
alert("All AJAX requests completed");
});
12. .ajaxSend()
$(document).ajaxSend(
function(event,xhr,options))
A function to run when
an AJAX requests is
about to be sent.
$(document).ajaxSend(function(e, xhr,
opt){
$("div").append("<p>Requesting: " +
opt.url + "</p>");
});
13. .ajaxError()
$(document).ajaxError(
function(event,xhr,options,exc))
A function to be run
when an AJAX request
fails.
$(document).ajaxError(function(){
alert("An error occurred!");
});
14. .ajaxSuccess()
$(document).ajaxSuccess(
function(event,xhr,options))
A function to run when
an AJAX request is
successfully completed.
$(document).ajaxSuccess(function(){
alert("AJAX request successfully
completed");
});
Topic 6: Plugin
Introduction
A jQuery plugin is a piece of code that extends the functionality of the jQuery library, which is a popular JavaScript framework used for
simplifying web development tasks, particularly DOM manipulation and event handling.
In Jquery Plug-in is a code that is needed in a standard javascript file.
Plugins help in providing different methods that can be used with different jquery library methods.
jQuery plugins allow developers to add specific features or behaviors to their websites by encapsulating reusable code in a modular way.
19. IT2304 – Full Stack Web Development Unit I - JQUERY
Prepared by Dr. R. Arthy, AP/IT 19
Common jQuery Plugins:
jQuery UI: A collection of user interface interactions, widgets, and effects built on top of jQuery. It provides components like date
pickers, sliders, dialog boxes, and more.
Slick: A responsive carousel/slider plugin that allows you to create attractive and interactive image sliders with various transition effects.
Colorbox: A lightbox plugin that enables you to display images, videos, and other types of content in a popup overlay.
jQuery Validate: A form validation plugin that makes it easier to add client-side validation to your forms, helping users input valid data.
Chosen: A plugin for enhancing select boxes (dropdown lists) by adding search, filtering, and better user experience.
Isotope: A filtering and sorting plugin for creating dynamic and animated grid layouts.
Magnific Popup: A lightweight and responsive lightbox plugin for displaying images, videos, and other content in a stylish manner.
FitVids.js: A plugin for responsive video embedding that automatically adjusts embedded videos to fit the container's width.
FullCalendar: A comprehensive calendar plugin that allows you to display events and schedules in a visually appealing way.
WOW.js: A plugin for adding CSS animations to elements as users scroll down the page.
Example – jQuery UI:
<!DOCTYPE html>
<html>
<head>
<title>jQuery UI Datepicker Example</title>
<link rel="stylesheet" href="./jquery-ui.css">
<script src="./jquery-3.6.0.min.js"></script>
<script src="./jquery-ui.js"></script>
</head>
20. IT2304 – Full Stack Web Development Unit I - JQUERY
Prepared by Dr. R. Arthy, AP/IT 20
<body>
<p>Select a date:</p>
<input type="text" id="datepicker">
<script>
$(document).ready(function() {
$('#datepicker').datepicker();
});
</script>
</body>
</html>
Create User Defined Plugin:
Creating the own jQuery plugin involves extending the $.fn object, which is jQuery's prototype for methods that can be called on jQuery-
selected elements.
Plugin's functionality and behavior can be defined by adding new methods to $.fn.
A basic structure for creating a jQuery plugin looks like this:
(function($) {
$.fn.myPlugin = function(options) {
// Your plugin code here
21. IT2304 – Full Stack Web Development Unit I - JQUERY
Prepared by Dr. R. Arthy, AP/IT 21
};
})(jQuery);
jQuery plugins can include methods that perform specific tasks.
These methods are called on selected elements, and they can modify the elements' content, appearance, behavior, etc.
Inside your plugin, you can define methods and use this.each() to iterate through the selected elements.
To enable chaining, you generally return this at the end of your plugin's methods.
(function($) {
$.fn.myPlugin = function(options) {
return this.each(function() {
// Your plugin's functionality for each selected element
});
};
})(jQuery);
Example:
alert.js
(function($) {
jQuery.fn.alertMethod = function() {
return this.each(function() {
alert('FSD in "' + $(this).prop("tagName") + '"tag');
});
};
22. IT2304 – Full Stack Web Development Unit I - JQUERY
Prepared by Dr. R. Arthy, AP/IT 22
})(jQuery);
Print.html
<html>
<head>
<script type = "text/javascript" src = “jquery.js">
</script>
<script src = "alert.js" type = "text/javascript">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("p").alertMethod();
});
</script>
</head>
<body>
<p>Full Stack Web Development</p>
</body>
</html>