• jQuery Video Tutorials

jQuery Cheatsheet



jQuery simplifies JavaScript code. It reduces the JavaScript code into a single line of code. It is a fast, small, and feature-rich JavaScript library. It makes easy interaction between HTML and CSS documents, DOM, and JavaScript. jQuery is designed to simplify HTML document traversal and manipulation, event handling, animation, and Ajax with an easy-to-use API that supports multiple browsers.

Table of Content

  1. Introduction to jQuery
  2. jQuery Basics
  3. jQuery Selectors
  4. jQuery Methods
  5. jQuery Manipulation Methods
  6. jQuery Traversing Method
  7. jQuery Events
  8. jQuery Effects
  9. jQuery Ajax Methods
  10. jQuery Core

1. Introduction to jQuery

jQuery is a lightweight JavaScript library that is speedy, fast and concise. This library was created by John Resig in 2006.

jQuery has been designed to simplify HTML DOM tree traversal and manipulation, as well as event handling, CSS animation, and Ajax.

Following is the principle of the jQuery −

  • Separation of JavaScript and HTML: It encourages developers to completely separate JavaScript code from HTML markup.
  • Brevity and clarity: It promotes features like chainable functions and shorthand function names.
  • Eliminates of cross-browser incompatibilities: Developers does not need to worry about browser compatibility while writing code using jQuery library.
  • Extensibility: It means new events, elements, and methods can be easily added in jQuery library and then reused as a plug-in.

2. jQuery Basics

jQuery is a lightweight and feature-rich JavaScript library. It simplifies the overall complexity of the code by implementing the Selectors, Attributes, Events, and Effects through the use of the required API to perform the suitable task. jQuery basics

jQuery Download

There are two versions of jQuery compressed and uncompressed. The compressed version is useful for production and faster execution. Where an uncompressed version is useful for the development of easy debugging. Visit official website

jQuery CDN Link

<script src="https://code.jquery.com/jquery-3.7.1.js" crossorigin="anonymous"></script>

Following is the features of the uncompressed −

  • Readable & Developer-Friendly: Includes proper indentation, space, and comments.
  • Easier Debugging: You can easily read and modify the code if needed.
  • Larger File Size: It has unnecessary space and comments, it loads slower in production.
  • Use Case: Preferred for development and debugging.

Following is the features of the compressed −

  • Optimized for Performance: It removes spaces, comments, and unnecessary characters.
  • Smaller File Size: Loads faster in production environment.
  • Hard to Read: Everything in single line, making debugging difficult.
  • Use Case: Best for production environment to improve website speed.

Example: Basic Example of jQuery

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

<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>JQuery-Practice</title>
</head>

<body>
   <p>I am Pargraph </p>
</body>
<script src="https://code.jquery.com/jquery-3.7.1.js" crossorigin="anonymous"></script>
<script>
   // implementing jQuery
   $(document).ready(function(){
	   $('p').click(function(){
		 console.log('Paragraph clicked!...')
	   })
	 })
</script>

</html>

jQuery Selectors

jQuery selectors are tools that allow the manipulation and selection of HTML elements within a webpage. They use CSS-like syntax, making it easier to interact with and modify the DOM. Following is the jQuery selector syntax −

$(document).ready(function(){
	$(selector)
});

jQuery Selectors can find HTML elements based on the following:

  • *: It selects all the HTML elements.
  • HTML element Name: It represent an HTML element name available in the DOM.
  • Element ID: It represents the HTML element with the id name of that element.
  • Element Class: It represents the HTML element with the class name of that element.
  • Element attribute name: It is used, to select the HTML element by its attribute name.
  • Element attribute value: It is used, to select the HTML element by its attribute name.

Example

Following is an example that demonstrates the use of selection and how we can use the selection in jQuery −

<!DOCTYPE html>
<html lang="en">
  <head>
	<title>JQuery-Practice</title>
  </head>
  <body>
	<h1>jQuery Selector</h1>
	<p id="myFirstId">
	  Lorem Ipsum is simply dummy text of the printing and typesetting industry
	</p>
	<p class="myFirstClass">
	  Lorem Ipsum is simply dummy text of the printing and typesetting industry
	</p>
	<div class="firstDiv" style="border: 1px solid">
	  <p>The first paragraph in div.</p>
	  <p>The last paragraph in div.</p>
	</div>
	<div id="divSecond" style='height: auto'>tutorialspoint</div>
  </body>
  <script src="https://code.jquery.com/jquery-3.7.1.js"></script>
  <script>
	$(document).ready(function () {
	  // select by element name
	  $("h1").css("background-color", "gray");

	  // select by id
	  $("#myFirstId").show(1000, function () {
		console.log("Element is visible");
	  });

	  // select by class name
	  $(".myFirstClass").hide(1000);

	  // select by child element
	  $("div p:first").css("color", "red");

	  // select by attribute name
	  $(".firstDiv[style]").css("background-color", "Orange");

	  // select by attribute value
	  $("#divSecond[style='height: auto']").css({
		'color': "green",
		"font-size": "20px",
		'padding': "10px",
		'border': "2px solid black",
	  });
	});
  </script>
</html>

jQuery Methods

In jQuery, methods are used to set or return the DOM attributes for specific elements. The following is a list of methods with their descriptions −

Method Description Syntax
prop() This method sets and return properties and values for the selected elements $(selector).prop(parameters)
removeAttr() This method remove attribute from the selected elements. $(selector).removeAttr(attribute)
removeProp() This method remove the property set by prop method. $(selector).removeProp(property)
val() This method return or set the value of attribute for selected element. $(selector).val()
removeData() This method remove data which was previously set. $(selector).removeData(args);
data() This method attaches or gets data for the selected elements. $(selector).data(parameters);
height() This method check the height of an element. $("selector").height()
innerHeight() This method check the height of an element. $("selector").innerHeight()
width() This method check the width of an element. $("selector").width()
innerWidth() This method check the inner width of an element $("selector").innerWidth()
css() This method changes the style property of the selected element. $(selector).css(property)
addClass() This method adds more property to the each selected element. $(selector).css(property)
removeClass() This method removes class name from the selected element. $(selector).removeClass(className, function(index, current_class_name))
hasClass() This method check if the element with specified class name exists. $(selector).hasClass(className);
toggleClass() This method changes the class attached with selected element. $(selector).toggleClass(class, function, switch)
scrollTop() This method returns the vertical top position of the scrollbar. $(selector).scrollTop(position)
scrollLeft() This method sets and return the horizontal position of the scroll bar. $(selector).scrollLeft(position)

Example

In the following example, we will demonstrate some of the above-listed methods and how they work in jQuery −

<!DOCTYPE html>
<html lang="en">
  <head>
	<title>JQuery-Practice</title>
  </head>
  <body>
	<h1>jQuery Selector</h1>
	<p id="myFirstId">
	  Lorem Ipsum is simply dummy text of the printing and typesetting industry
	</p>
	<div class="firstDiv" style="border: 1px solid">
	  <p>The first paragraph in div.</p>
	  <p>The last paragraph in div.</p>
	</div>
	<div id="divSecond" style='height: auto'>tutorialspoint</div>
  </body>
  <script src="https://code.jquery.com/jquery-3.7.1.js"></script>
  <script>
	$(document).ready(function () {
	  // apply css on h1 element
	  $("h1").css("background-color", "gray");

	  // set properties of first div
	  $("#myFirstId").prop("title", "This is my first paragraph");

	  // return the value of title property
	  var title = $("#myFirstId").prop("title");
	  console.log(title);

	  // remove attribute from selected element
	  $(".firstDiv").removeAttr("style");

	  // get data from divSecond
	  var data = $(".firstDiv").data("name");
	  console.log(data);

	  // check height of divSecond
	  var height = $("#divSecond").height();
	  console.log(height);

	  // check innderwidth of divSecond
	  var innerWidth = $("#divSecond").innerWidth();
	  console.log(innerWidth);
	});
  </script>
</html>

jQuery Manipulation Methods

There are different kinds of manipulation methods on jQuery that can be used to manipulate the DOM. This method can be categorized in two ways.

Setter

In the setter, there are various methods available. Some methods are designed to change the attributes of an element, while others set the type properties of the element. Additionally, there are some methods that can modify entire elements or groups of elements by allowing actions such as inserting, copying, and removing.

Getter

Several methods work as getter method, such as attr(), html(), and val(), which can be used to retrieve information from DOM elements for further use.

Method Description Syntax
append() Insert content at the end of selected elements. $(selector).append( content, function(index, html) )
appendTo() Insert an HTML element at the end of the selected element. $(content).appendTo(selector)
html() Sets or return the innerHTML content to selected element. $(selector).html(function(index, currentcontent))
prependTo() Insert an HTML element at the beginning of the selected element. $(content).prepend(selector)
text() Sets or returns the text content of the element. $(selector).text(function(index, content))
clone() Makes a copy of the selected elements including its child. $(selector).clone()
insertBefore() Insert HTML content before a specified element. $(content).insertBefore(target)
insertAfter() Insert HTML content after specified element. $(content).insertAfter(target)
detach() Remove the selected elements from the DOM tree. $("selector").detach()
empty() Remove all child node and their content for selected elements. $("selector").empty()
remove() Remove all the selected elements including the text. $(selector).remove(property)
replaceWith() Replace the selected element with the new one. $(selector).replaceWith(content, function)
wrapAll() Used to wrap specified element against all the selected elements. $(selector).wrapAll(wrap_element)

Example

In the following example, we demonstrate the use of the manipulation method and how these methods work in jQuery −

<!DOCTYPE html>
<html lang="en">
  <head>
	<title>JQuery-Practice</title>
  </head>
  <body>
	<h1>jQuery Selector</h1>
	<p id="myFirstId">
	  Lorem Ipsum is simply dummy text of the printing and typesetting industry
	</p>
	<p id="mySecondPara">This is second paragraph</p>
	<div class="firstDiv" style="border: 1px solid">
	  <p>The first paragraph in div.</p>
	  <p>The last paragraph in div.</p>
	</div>
	<div id="divSecond" style='height: auto'>tutorialspoint</div>
	<ol>
	  <li>tutorialspoint</li>
	</ol>
	<button id="firstbtn">first btn</button>
	<button id="secondbtn">second btn</button>
	<button id="thirdbtn">third btn</button>
	<button id="fourthbtn">insert btn</button>
	<button id="fivethbtn">empty btn</button>
	<button id="sixthbtn">remove btn</button>
  </body>
  <script src="https://code.jquery.com/jquery-3.7.1.js"></script>
  <script>
	$(document).ready(function () {
	  // return the inner HTML content
	  var content = $("#myFirstId").html();
	  console.log(content);

	  $("#firstbtn").click(function(){
		 // return the text content
		 $("#mySecondPara").text(function(){
			return "changing the content of para 2";
		 });
	  })

	  $("#secondbtn").click(function () {
		 // appen the list append()
		 $("ol").append("<li>Append Tp</li>");
	  });

	  $("#thirdbtn").click(function () {
		 // prepend the list using prepend()
		 $("<span>jQuery Tutorialspoint</span>").prependTo("h1");
	  });

	  // insertBefore() method
	  $(".firstDiv").click(function(){
		 $("<p>Inserted before the second para</p>").insertBefore("#mySecondPara");
	  });

	  // insertAfter() method
	  $("#fourthbtn").click(function(){
		 $("<p>I am tutorialspoint</p>").insertAfter("#mySecondPara");
	  });

	  // empty() method
	  $("#fivethbtn").click(function(){
		 $(".firstDiv").empty();
	  });

	  // remove() method
	  $("#sixthbtn").click(function(){
		 $(".firstDiv").remove();
	  });
	});
  </script>
</html>

jQuery Traversing Method

In jQuery traversing stands for moving through or HTML element to find filter or select the particular or entire element based on the traversing. Following are the list of traversing method −

Method Description Syntax
children() Finds all the child element related to selected element. $(selector).children()
parent() Finds the parent element related to the selected element $(selector).parent()
next() Returns the next sibling of the selected element. $(selector).next()
closest() Returns the first ancestor of the selected element in the DOM tree. $(selector).closest(parameters);
prevUntil() Finds all the previous sibling element between two elements. $(selector1).nextUntil(selector2)
siblings() Finds all the siblings elements of the selected element. $(selector).siblings(function)
first() Selects the first element from the specified elements. $(selector).first()
last() Finds the last element from the specified elements $(selector).last()
is() Checks one of the selected elements matches the selectorElements. $(selector).is(selectorElement, function(index, element))
map() Translates all items in an array or object to a new array. jQuery.map( array/object, callback )
filter() Returns the elements which matches the given conditions. $(selector).filter(criteria, function(index))
not() Returns all elements which do not match the selected element. $(selector).not(A)
each() Specifies the function to run for each matched element. $(selector).each(function(index, element))
find() Finds all the descendent elements of selected element. $(selector).find()

Example

Following is an example of the jQuery traversing method. Here, we demonstrate how we can use this method −

<!DOCTYPE html>
<html lang="en">
  <head>
	<title>JQuery-Practice</title>
  </head>
  <body>
	<h1>jQuery Traverse Method</h1>
	<h3>jQuery children() Method</h3>
	<div class="firstDiv" style="width: 500px">
	  This is the current element !!!
	  <p class="first">
		This is the first paragraph element !!!
		<span>This is grandchild</span>
	  </p>
	  <p class="second">
		This is the second paragraph element !!!
		<span>This is grandchild</span>
	  </p>
	</div>
	<hr />
	<div class="secondDiv">
	  This is parent element !
	  <p>This is first paragraph</p>
	  <span>first span box </span>
	  <h2>heading 2 !</h2>
	  <h3>jQuery next() Method</h3>
	  <p>This is the second paragraph and next sibling to h3 !</p>
	</div>
	<hr />
	<div class="main" style="width: 600px">
	  This is great grand parent element !
	  <ul>
		This is the second ancestor element !
		<ul>
		  This is first ancestor element !
		  <li>
			This is direct parent !
			<span>jQuery closest() Method</span>
		  </li>
		</ul>
	  </ul>
	</div>
	<hr />
	<div class="main_div">
	  <div style="width: 500px">
		div (Great-Grandparent)
		<ul>
		  This is the grand-parent of the selected span element.!
		  <li>
			This is the parent of the selected span element.!
			<span>jQuery parent() Method</span>
		  </li>
		</ul>
	  </div>
	</div>
	<hr />
	<div style="width: 400px" class="sib1">
	  <ul>
		This is parent !!!
		<li class="stop">list 1 !!!</li>
		<li>jQuery prevUntil() Method</li>
		<li>first list !</li>
		<li>second list !</li>
		<li class="start">list 5 !!!</li>
		<li>other sibling</li>
		<li>other sibling</li>
	  </ul>
	</div>
	<hr />
	<div class="sib2">
	  This is parent!!!
	  <p>This is paragraph!!!</p>
	  <span>This is span box!!!</span>
	  <h2>jQuery siblings() Method</h2>
	  <h3>This is heading 3!</h3>
	</div>
	<hr />
	<div id="div1" style="border: 1px solid rgb(21, 0, 128)">
	  <p>jQuery first() Method</p>
	</div>
	<br />
	<div style="border: 1px solid rgb(21, 0, 128)">
	  <p>This is the second statement.</p>
	</div>
	<br />
	<div id="div2" style="border: 1px solid rgb(21, 0, 128)">
	  <p>jQuery last() Method</p>
	</div>
	<hr />
	<section id="div3">
	  <h6 id="pid">
		jQuery is() Method - Click me to find out if I my parent is a section
		element.
	  </h6>
	</section>
	<hr />
	<ul>
	  <li id="first">jQuery filter() Method</li>
	  <li id="middle">Tutorialspoint</li>
	  <li id="last">India</li>
	</ul>
	<hr />
	<h5 id="main_content">I am Tutorialspoint.!!!</h5>
	<h5>This is jQuery not() Method.</h5>
	<hr />
  </body>

  <script src="https://code.jquery.com/jquery-3.7.1.js"></script>
  <script>
	$(document).ready(function () {
	  // children()
	  $(".firstDiv").children("p.first").css({
		color: "green",
		border: "2px solid gray",
	  });
	});

	$(document).ready(function () {
	  // next()
	  $("h3").next().css({
		border: "2px solid gray",
	  });
	});

	$(document).ready(function () {
	  // closest()
	  $("span").closest("ul").css({
		color: "orange",
		border: "2px solid red",
	  });
	});

	$(document).ready(function () {
	  // parent()
	  $("#inner").parent().css({
		color: "green",
		border: "2px solid green",
	  });
	});

	$(document).ready(function () {
	  // siblings()
	  $("h2").siblings().css({
		color: "black",
		border: "2px solid green",
	  });
	});

	$(document).ready(function () {
	  // first()
	  $("#div1").first().css("background-color", "lightgreen");
	});

	$(document).ready(function () {
	  // last()
	  $("#div2").last().css("background-color", "lightblue");
	});

	$(document).ready(function () {
	  // is()
	  $("h6").click(function () {
		if ($("h6").parent().is("#div3")) {
		  alert("Parent of <h6> is <section>");
		}
	  });
	});

	$(document).ready(function () {
	  // filter()
	  $("li").filter("#first, #last").css("color", "blue");
	});

	$(document).ready(function () {
	  // not()
	  $("h5")
		.not("#main_content")
		.css("color", "orange")
		.css("font-size", "20px");
	});
  </script>
</html>

jQuery Events

The Events refers to the action performed by the user or visitor who visited the site during their activity with the website. An event can be a button click, mouse hover, mouse pointer movement over the image, any key pressed from the keyboard, etc. Following is the list of events −

Events Description Syntax
on() Attached on or more handler to the selected elements and child elements. $(selector).on(event, childSelector, data, function)
one() Attached one or more handler to the selected element. $(selector).one(event, data, function)
off() Removes event handler attached with the on method. $(selector).off(event, selector, function(eventObj), map)
bind() Attached event handler to the selected element. $(selector).bind(event, data, function);
blur() Used to remove the focus from the selected element. $(selector).blur(function)
resize() It trigger when the browser window change the size. $(selector).resize(function)
scroll() Used to scroll in specified element. $(selector).scroll(function)
load() It loads data from the server and return them to the selected elements. $(selector).load(URL, data, callback);
trigger() Triggers a specified event handlers to the selected elements. $(selector).trigger(event,parameters)
click() Starts the click event or attached a function to return when click event occurs. $(selector).click(function);
hover() Specifies function to start when mouse pointer moves over selected element. $(selector).hover(Function_in, Function_out);
mouseover() It works when mouse pointer moves over the selected elements. $(selector).mouseover(function)
toggle() Checks the visibility of the selected elements to toggle. $(selector).toggle(speed, easing, callback)
keyup() It is used to trigger the keyup event whenever the user release a key from the keyboard. $(selector).keyup(function)
preventDefault() Used to prevent the default action of the selected element to occur. event.preventDefault()

Example

In the following example, we demonstrate event methods and how they work in jQuery −

<!DOCTYPE html>
<html lang="en">
  <head>
	<title>JQuery-Practice</title>
  </head>
  <body>
	<h2>jQuery Events Method</h2>
	<p class="firstPara">This is first Paragraph !!!</p>
	<button id="btn1">Click me</button>
	<button id="btn2">blured me</button>

	<div class="parent">
	  <p>This is parent div</p>
	  <div class="nested" tabindex="0">
		<p>This is nested div</p>
	  </div>
	</div>
	<p id="bind">Using Bind here!!!</p>
	<button id="btn3">One Method Click me!</button>
	<p class="secondPara">
	  Toggle method, I am toggling after 3 sec. Lorem ipsum dolor sit amet
	  consectetur adipisicing elit. At odio asperiores obcaecati necessitatibus
	  blanditiis facere magni voluptates eligendi, libero animi quae tenetur.
	  Porro reprehenderit labore temporibus voluptatum quis consectetur aliquid.
	</p>
	<button id="btn4">Click me for off!</button>
  </body>

  <script src="https://code.jquery.com/jquery-3.7.1.js"></script>
  <script>
	$(document).ready(function () {
	  // using the click method
	  $("#btn1").click(function () {
		alert("Button 1 clicked");
	  });

	  // using the hover method
	  $("h2")
		.hover(function () {
		  alert("Hovered over h2");
		})
		.css({ color: "blue", cursor: "pointer", backgroundColor: "yellow" });

	  // mouseover method
	  $(".firstPara").mouseover(function () {
		alert("Mouse over first paragraph");
	  });

	  // using blur method
	  $("#btn2").blur(function () {
		alert("Button 2 blured");
	  });

	  // using on method
	  $(".parent").on("click", function () {
		alert("Parent div clicked");
	  });

	  // using focus with on method
	  $(".nested")
		.focus(function () {
		  console.log("Nested div focused");
		})
		.css({ color: "red", border: "1px solid gray" });
	});

	//using bind method
	$("#bind").bind("click", function () {
	  alert("Bind method used");
	});

	// using one method
	$("#btn3").one("click", function () {
	  // one()
	  $(".parent").animate({
		fontSize: "+=14px",
		backgroundColor: "yellow",
		padding: "+=10px",
	  });
	});

	// using toggl method
	$(".secondPara").toggle(4000, function () {
	  alert("Toggle method used");
	}); // 4 sec

	//using load method
	$(window).load(function () {
	  alert("Window loaded");
	});

	//using off method
	$("#btn4").click(function () {
	  alert("Button 1 clicked");
	  $(this).off("click");
	});
  </script>
</html>

jQuery Effects

jQuery effects are pre-built visual effects animation and transitions that can be applied to HTML elements. The effects are the parts of the jQuery library that simplify the process of adding dynamic behaviour to web pages. Following is the list of jQuery effects −

Effects Description Syntax
hide() It is used to hide the selected element. $(selector).hide(duration, call_function);
show() Used to display hidden and selected elements. $(selector).show(speed, callback)
toggle() Check the visibility of selected element to toggle. $(selector).toggle(speed, callback)
animate() Used to change the state of element with CSS style. $(selector).animate({style}, para...)
delay() Set a timer to delay the execution in the queue. $(selector).delay(para1, para2);
finish() Used to stop the animation running at present time. $(selector).finish();
clearQueue() Removes all items in the queue that have not yet been run. $(selector).clearQueue(name);
dequeue() Removes the next function from the queue and executes it. $(selector).dequeue(name);
fadeIn() Used to changes the opacity of the selected elements. $(selector).fadeIn(speed, callback)
fadeOut() Changes the level of opacity for selected element. $(selector).fadeOut(speed, callback )
fadeTo() Changes the opacity of the selected element. $(selector).fadeTo(opacity, call_function)
fadeToggle() Toggles between fadeIn and fadeOut methods. $(selector).fadeToggle()
queue() Used to show the queue of function to be executed. $(selector).queue(queue_name)
stop() Used to stop the currently running animations $(selector).stop(stopAll, goToEnd);

Example

Following is an example of the jQuery effects methods. Here, we demonstrate and use the effects on the HTML element −

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>JQuery-Practice</title>
  </head>
  <body>
    <h2>jQuery Effects Methods −</h2>
    <p id="hide-show">
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Ullam ut iure,
      dolorem maxime, nulla recusandae ab a ipsam minima deleniti aliquid.
      Corrupti, incidunt vel omnis tempora aliquid similique dicta architecto.
    </p>
    <button id="toggle">Toggle heading</button>
    <p id="fadeIn">
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Eaque
      exercitationem autem non aspernatur veniam placeat velit, deleniti odio
      laudantium perspiciatis aperiam molestiae nobis nisi? Quod fuga temporibus
      quasi saepe eum.
    </p>
    <p id="fadeOut">
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Ex iure vel id
      tempora minus doloremque, eveniet inventore aperiam, a dignissimos rem
      quos est animi, amet magnam iusto omnis. Cupiditate, atque?
    </p>

    <div id="div1">
      I am division First. Lorem ipsum dolor sit amet consectetur adipisicing
      elit. Iusto rem repudiandae vel ratione quae modi et.
    </div>
    <button id="fadetoggle">FadeToggle</button>

    <p id="slideUp">
      <span>Slide Up</span> Lorem ipsum dolor sit amet, consectetur adipisicing
      elit. Veritatis reiciendis similique, commodi enim consectetur, ducimus ut
      expedita nostrum
    </p>
    <button id="finish">Finish Sliding up</button>
    <p id="slideDown">
      <span>Slide Down</span> Lorem ipsum dolor sit amet, consectetur
      adipisicing elit. Veritatis reiciendis similique, commodi enim
      consectetur, ducimus ut expedita nostrum
    </p>

    <div
      id="queueDiv"
      style="
        width: 200px;
        height: 100px;
        background-color: lightgray;
        margin-top: 20px;
      "
    >
      <p id="queuePara">This is a queued animation example.</p>
    </div>
    <button id="startQueue">Start Queue</button>
    <button id="dequeue">Dequeue</button>
  </body>

  <script src="https://code.jquery.com/jquery-3.7.1.js"></script>
  <script>
    $(document).ready(function () {
      // using hide method
      $("#hide-show").hide(3000, function () {
        console.log("The paragraph is now visible");
      });
      // using show method
      $("#hide-show").show(2000, function () {
        console.log("The paragraph is now visible");
      });

      // using toggle method
      $("#toggle").click(function () {
        $("h2").toggle(2000);
      });

      // using fadeIn method
      $("#fadeIn").fadeIn(4000, function () {
        console.log("paragraph is fadded in! ");
      });

      // using fadeOut method
      $("#fadeOut").fadeOut(4000, function () {
        console.log("paragraph is fadded in! ");
      });

      // using fadeToggle method
      $("#fadetoggle").click(function () {
        $("#div1")
          .fadeToggle(2000, function () {
            console.log("Fade toggle is working");
          })
          .css({
            "background-color": "blue",
            color: "white",
            padding: "10px",
            border: "none",
            "border-radius": "5px",
          });
      });

      // using slideUp method
      $("#slideUp").slideUp(3000, function () {
        console.log("Sliding up");
      });

      // using finish method
      $("#finish").click(function () {
        $("#slideUp").finish(); // Immediately complete the animation
        console.log("Finished sliding up");
      });

      // using slideDown method
      $("#slideDown").slideDown(5000, function () {
        console.log("Sliding down");
      });

      // using stop method
      $("#slideDown").click(function () {
        $(this).stop(); // Stop the animation
        console.log("Stopped sliding down");
      });

      // using queue method
      $("#startQueue").click(function () {
        $("#queueDiv")
          .queue(function (next) {
            $(this).css("background-color", "yellow");
            console.log("Step 1: Background color changed to yellow");
            next();
          })
          .queue(function (next) {
            $(this).animate({ width: "300px" }, 2000);
            console.log("Step 2: Width increased to 300px");
            next();
          })
          .queue(function (next) {
            $(this).animate({ height: "150px" }, 2000);
            console.log("Step 3: Height increased to 150px");
            next();
          });
      });

      // Using dequeue method
      $("#dequeue").click(function () {
        $("#queueDiv").dequeue();
        console.log("Dequeued the next animation step");
      });
    });
  </script>
</html>

jQuery Ajax Methods

There are various methods and functions in jQuery for Ajax functionality that allow the loading of data from the server without refreshing the browser page. Ajax is used on the client side to create asynchronous web applications. Some of the jQuery AJAX methods are used to request text, HTML, XML, or JSON from a remote server using both HTTP Get and HTTP Post. The following is the list of methods.

AJAX Methods Description Syntax
ajax() Performers an Ajax request or asynchronous HTTP request. jQuery.ajax({name:value, name:value, … })
ajaxSetup() Sets the default value for the future ajax request. jQuery.ajaxSetup( {name:value, name:value, … } )
get() Loads the data from the server by using the HTTP Get request. jQuery.get( url, [data], [callback], [type] )
getJSON() Fetches JSON-encoded data from the server using the HTTP Get request. $(selector).getJSON(url,data,success(data,status,xhr))
getScript() Runs the JavaScript using AJAX HTTP Get Request. $(selector).getScript(url, success(response, status))
param() Creates a serialized representation of an object. jQuery.param(obj, traditional);/td>
post() Loads the page from the server using a HTTP Post. jQuery.post( url, data, callback_function, data_type )
ajaxError() Specifies functions to run when an AJAX request fails. $(document).ajaxError( function(event, xhr, options, exc) )
ajaxStart() Specifies functions to run when an AJAX request starts. $(document).ajaxStart(function())
ajaxStop() Specifies functions to be executed when an AJAX request have been completed. $(document).ajaxStop(function())
load() Loads data from the server and returned into selected element. $(selector).load(URL, data, callback);
serialize() Creates a text string in standard URL-encoded notation. $(selector).serialize()
serializeArray() Create a JavaScript array of objects to be encod as a JSON string. $(selector).serializeArray()

Example

Following is an example of the jQuery AJAX method. Here, we demonstrate them and use them −

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>jQuery AJAX Example</title>
  </head>
  <body>
    <button id="fetchData">Fetch Data</button>
    <br />
    <button id="postData">Post Data</button>
    <br />
    <button id="fetchJson">Fetch JSON</button>
    <br />
    <button id="putData">Update Data</button>
    <br />
    <button id="deleteData">Delete Data</button>
    <hr />
    <div id="result"></div>
  </body>
  <!-- jQuery CDN -->
  <script src="https://code.jquery.com/jquery-3.7.1.js"></script>
  <!-- jQuery implementation -->
  <script>
    $(document).ready(function () {
      $("button").css({
        "background-color": "blue",
        color: "white",
        padding: "10px",
        border: "none",
        "border-radius": "5px",
        margin: "5px",
      });
    });

    $(document).ready(function () {
      $("#fetchData").click(function () {
        // using ajax method
        $.ajax({
          url: "https://jsonplaceholder.typicode.com/posts/1",
          type: "GET",
          dataType: "json",
          success: function (data) {
            $("#result").html(
              "<h3>" + data.title + "</h3><p>" + data.body + "</p>"
            );
          },
          error: function (xhr, status, error) {
            console.log("Error: " + error);
          },
        });
      });

      // using post method
      $("#postData").click(function () {
        $.post(
          "https://jsonplaceholder.typicode.com/posts",
          {
            title: "New Post",
            body: "This is the body of the post.",
            userId: 1,
          },
          function (data) {
            console.log("Post Success:", data);
            $("#result").html("<p>Post Created: " + data.id + "</p>");
          },
          "json"
        );
      });

      // using getJSON method
      $("#fetchJson").click(function () {
        $.getJSON(
          "https://jsonplaceholder.typicode.com/posts/2",
          function (data) {
            $("#result").html(
              "<h3>" + data.title + "</h3><p>" + data.body + "</p>"
            );
          }
        );
      });

      $("#putData").click(function () {
        $.ajax({
          url: "https://jsonplaceholder.typicode.com/posts/1",
          type: "PUT",
          data: JSON.stringify({
            id: 1,
            title: "Updated Post",
            body: "This is the updated body of the post.",
            userId: 1,
          }),
          contentType: "application/json; charset=UTF-8",
          success: function (data) {
            console.log("Put Success:", data);
            $("#result").html("<p>Post Updated: " + data.id + "</p>");
          },
        });
      });

      $("#deleteData").click(function () {
        $.ajax({
          url: "https://jsonplaceholder.typicode.com/posts/1",
          type: "DELETE",
          success: function () {
            console.log("Delete Success");
            $("#result").html("<p>Post Deleted</p>");
          },
        });
      });

      // using load method
      $("#loadText").click(function () {
        $("#result").load("sample.txt"); // load()
      });

      // using ajaxSetup method
      $("#ajaxSetupBtn").click(function () {
        $.ajaxSetup({
          url: "sample.txt",
          success: function (data) {
            $("#result").html(data);
          },
        });
        $.ajax();
      });
    });
  </script>
</html>

jQuery Core

jQuery enables the DOM Element Methods, properties, utilities, jQuery Object, delayed Object, Callbacks Object, and others to provide functions with modifications that improve the overall interactivity of the website. Following is the list of methods −

Methods/Properties Description Syntax
jQuery.Deferred() Returns the utility object with method to register multiple callbacks to queues. jQuery.Deferred([beforeStart])
deferred.then() Adds handlers which are called on the differed objects. deferred.then(doneCallbacks[, failCallbacks][, progressCallbacks])
deferred.done() Adds handler which are called when differed objects is resolved. deferred.done(Callbacks [, Callbacks])
.promise() Returns a promise object to be observed when certain actions are ended. .promise([type][, target])
deferred.always() Adds handlers which are called when deffered object is resolved or rejected. deferred.always( alwaysCallbacks [, alwaysCallbacks] )
deferred.fail() Adds handler which are to be called when deffered object is rejected. deferred.fail(failedCallbacks, failedCallbacks )
index() Returns the index of the specified elements with respect to selector. $(selector).index(element)
jQuery.when() Executes callback functions depending on zero or more Thenable objects. jQuery.when(deferreds)
length() Counts the number of elements of the jQuery objects. $(selector).length
jQuery.each() Specifies the function to run for each method element. $(selector).each(function(index, element))
callback.fire() Returns the callbacks object onto which it is attached (this). callbacks.fire( arguments )
callback.lock() Locks a callback list in the state. callbacks.lock()

Example

In the following example, we will demonstrate the above-listed methods in jQuery and how they work on HTML elements.

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

<head>
   <meta charset="UTF-8" />
   <meta name="viewport" content="width=device-width, initial-scale=1.0" />
   <title>jQuery Deferred Example</title>
   <script src="https://code.jquery.com/jquery-3.7.1.js"></script>
</head>

<body>
   <h1>jQuery Deferred Demo</h1>
   <button id="startTask">Start Task</button>
   <p id="status">Click the button to start.</p>
   <!-- Elements for jQuery.each() and index() -->
   <div class="items">
      <div class="item" id="item1">Item 1</div>
      <div class="item" id="item2">Item 2</div>
      <div class="item" id="item3">Item 3</div>
   </div>
   <!-- Button to trigger callbacks -->
   <button id="fireCallbacks">Fire Callbacks</button>
   <script>
      $(document).ready(function () {

         $("#startTask").click(function () {
            function fetchData() {
               var deferred = $.Deferred();

               // Simulate a delay (asynchronous task)
               setTimeout(function () {
                  var success = true;
                  if (success) {
                     deferred.resolve("Task completed successfully!");
                  } else {
                     deferred.reject("Task failed!");
                  }
               }, 1000);
               return deferred.promise();
            }

            var task = fetchData();
            task
               .done(function (message) {
                  $("#status").text(message);
               })
               .fail(function (error) {
                  $("#status").text(error);
               })
               .always(function () {
                  console.log("Task finished!");
               });
         });
      });

      // jQuery.each() Example
      $(document).ready(function () {
         $(".item").each(function (index, element) {
            console.log("Index: " + index + ", Text: " + $(element).text());
         });

         // index() Example
         var idx = $(".item").index($("#item2"));
         console.log("Index of #item2: " + idx);

         // Callbacks Example
         var callbacks = $.Callbacks();

         callbacks.add(function () {
            $("#status").text("First callback executed!");
         });
         callbacks.add(function () {
            $("#status").append(" Second callback executed!");
         });

         // Button to fire callbacks
         $("#fireCallbacks").click(function () {
            // Fire all callbacks
            callbacks.fire();
         });

         // Locking callbacks
         $("#fireCallbacks").click(function () {
            // Locking prevents new additions
            callbacks.lock();
         });
      });
   </script>
</body>
</html>

Conclusion

This jQuery Cheat sheet is design to help you master all the jQuery concepts. After reading or particles of this cheat sheet you can able to develop any jQuery pages. This is a handy resource that summarizes essential concepts, functions methods, and selectors in jQuery. The jQuery library is the most powerful tool that simplifies the task like DOM manipulation, event handling, animations, and Ajax calls.

Advertisements