JQUERY CheatSheet
jQuery is a lightweight, "write less, do more", JavaScript library. jQuery is a JavaScript Library, simple, and easy. We can with JQuery
>HTML/DOM manipulation
>CSS manipulation
>HTML event methods
>Effects and animations
>AJAX
>Utilities
1.GET STARTED
Download from here http://jquery.com/download/ and add it into your project
<head>
<script src="jquery-3.7.1.min.js"></script>
</head>
Or Use Google CDN in head Tag
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
2. JQUERY SYNTAX
Basic syntax is:
$(selector).action()
$ to define/access jQuery , (selector) to find HTML elements, action() to be performed on the element(s)
>> To prevent any jQuery code from running before the document is finished loading use (is ready). It will allow code when all elements created and all images loaded properly
$(document).ready(function(){
// jQuery methods go here...
});
OR use shorter syntax
$(function(){
// jQuery methods go here...
});
3. SELECTORS IN JQUERY
1.select elements IE paragraph element
$("p");
2. select element that has id test ie <div id="test"> Hello</div>
$("#test")
3. select element that has class test <div class="test">hello </div>
$(".test")
4. More Examples of jQuery Selectors
$("*") Selects all elements
$(this) Selects the current HTML element
$("p.intro") Selects all <p> elements with class="intro"
$("p:first") Selects the first <p> element
$("ul li:first") Selects the first <li> element of the first <ul>
$("ul li:first-child") Selects the first <li> element of every <ul>
$("[href]") Selects all elements with an href attribute
$("a[target='_blank']") Selects all <a> elements with a target attribute value equal to "_blank"
$("a[target!='_blank']") Selects all <a> elements with a target attribute value NOT equal to "_blank"
$(":button") Selects all <button> elements and <input> elements of type="button"
$("tr:even") Selects all even <tr> elements
$("tr:odd") Selects all odd <tr> elements
$(":radio"); All input type=radio
$('input[type="radio"][value="option2"]').prop('checked', true); //enable check on radio input based on value
5. select more than one elements
$(".class1",".class2");
4. EVENTS IN JQUERY
syntax:
$("p").event(function(){
//CODE HERE
});
1. Binding
$(selector).bind(event, data, function);
function handlerName(e) {
alert(e.data.msg);
}
$(document).ready(function() {
$("p").bind("click",{ msg: "You just clicked the paragraph!"},handlerName)
});
2.on change input feild
$(selector).change(function(){});
3.Get x-axis or y-axis point
$(document).mousemove(function(event) {
alert("X= " + event.pageX);
alert("Y= " + event.pageY);
});
4.Return node name
$("body").click(function(event) {
$("#output").html("clicked: " + event.target.nodeName);
});
5.when event is used
$("#div1").on("click dblclick mouseover mouseout",function(event) {
$(".div2").html("Event: " + event.type);
});
6.return which keyboard key or mouse button was pressed
$("input").keydown(function(event) {
alert("Key: " + event.which);
});
7. when focus on some element ie when click inside input fiels
$(selector).focus(function(){});
8.gain focus on element
$(selector).focusin(function);
9.remove focus
$(selector).focusout(function);
10.mousein & mouse out
$(selector).hover(function(){},function(){});
11.when a keybord key is pressed down
$(document).keydown(function(event) {
var key =event.keyCode; //event.which
alert(key);
});
12.to check key is pressed or not.
$(selector).keypress(function([event]){});
13.when key is released
$(selector).keyup(function([event]){});
14.when left mouse button is pressed
$(selector).mousedown(function(){});
15.when mouse enters into selected element
$(selector).mouseenter(function(){});
16.when mouse pointer moves over the selected element.
$(selector).mousemove(function(){});
17.when mouse pointer moves out from the selected element.
$(selector).mouseout(function(){});
18.when mouse pointer moves over the selected elements.
$(selector).mouseover(function(){});
19.when left button of mouse is realeased
$(selector).mouseup(function(){});
20.when window resized
$(selector).resize(function(){});
21.when scroll element or body
$(selector).scroll(function(){});
22.remove event
$(selector).undelegate(selector, event, function);
23.load data from server and returned into selected element
$(selector).load(URL, data, callback);
$("#div_content").load("gfg.txt");
$("#div_content").load("gfg.txt", function(response, status, http){
if(status == "success"){}
if(status == "error"){alert("Error: " + http.status + ": "+ http.statusText);}
});
24.when leave input feild
$(selector).blur(function(){});
25.when click on element etc //also used for live elements ie if <li> added by jquery then click event is not working on that so use on
$(selector).on({event:function(){},event2:function(){},...});
Syntax: .on( events [, selector ] [, data ], handler )
$( "# tr" ).on( "click", function() {
console.log( $( this ).text() );
});
For dynamic code that are generated by js
$(document).on('click', '.cnicis', function() {
console.log('sss');
});
26.when double click on element
$(selector).dblclick(function(){});
5. Effects , hide,show, fades , slides , animate ,callback ,chaning ,delay
1.Hide & Show
$(selector).hide(speed,callback); //hide the element
$(selector).show(speed,callback); //show the element
$(selector).toggle(speed,callback); //show if the element is hidden & vv
$("p").hide(1000);
2. Fades
$(selector).fadeIn(speed,callback);
$(selector).fadeOut(speed,callback);
$(selector).fadeToggle(speed,callback);
$(selector).fadeTo(speed,opacity,callback); //opacity is added in fadding
$("#div3").fadeIn(3000);
$("#div2").fadeTo("slow", 0.4);
3. Slides
$(selector).slideDown(speed,callback); //slide down an element
$(selector).slideUp(speed,callback); //slide up an element
$(selector).slideToggle(speed,callback); //toggle b/w slide down and slide up
4. Animate
$(selector).animate({params},speed,callback);
$("button").click(function(){
$("div").animate({
left: '250px',
opacity: '0.5',
paddingLeft:'5px', //use camel case properties
height: '+=150px', //we can also use relative values
height: 'toggle' //we can also use properties now element height will be between 0-n
});
});
use queue to execute different animations after each other
$("button").click(function(){
var div = $("div");
div.animate({height: '300px', opacity: '0.4'}, "slow");
div.animate({width: '300px', opacity: '0.8'}, 2000);
div.animate({height: '100px', opacity: '0.4'}, "fast");
});
stop: to stop animations
$(selector).stop([stopAll,goToEnd]);
- stopAll:true|false //if false stop current queue else all queue
- goToEnd:true|false //complete current animation immediately
- both has default false value.
CallBack
A callback function is executed after the current effect is finished.
syntax: $(selector).hide(speed,callback);
$("p").hide("slow", function(){
alert("The paragraph is now hidden");
});
it ll first hide <p> then alert, by default alert is executed first
Chaning: use multiple jquery methods at same time w/o selecting element multiple times
$("#p1").css("color", "red").slideUp(2000).slideDown(2000);
Delay: delay and then execute
$("#d3").delay(1000).fadeIn();
6. JQUERY HTML Get elements, Set elements, Add elements, remove elemets, CSS set,get, Dimentions
1. GET HTML ELEMENTS
$(selector).text(); // get plain text of element
$(selector).html(); // get html of element
$(selector).val(); // value of form fields
$(selector).attr("atributeName"); //get attribute name
2. SET HTML ELEMENTS
$(selector).text("hello"); //set text of element
$(selector).html("<p>hy</p>");
$(selector).val("Enter Name");
$(selector).attr("atributeName","value");
$("#rizi").attr("href","gondal");
For Multiple Attributes
$("#w3s").attr({
"href" : "https://www.google.com/",
"title" : "Google"
});
3. ADD NEW DATA
$(selector).append("insert content at end of selected element"); //text or html added
$(selector).prepend("insert content at begning of selected");
$(selector).after("insert content after selected element");
$(selector).before("insert content before selected element");
var txt1 = "<p>Text.</p>"; // Create element with HTML
var txt2 = $("<p></p>").text("Text."); // Create with jQuery
var txt3 = document.createElement("p"); // Create with DOM
txt3.innerHTML = "Text.";
$("body").append(txt1, txt2, txt3); // Append the new elements
4. REMOVE DATA
$(selector).remove();//remove selected element and its childs
$(selector).empty();//remove childs of selected element
ie $("p").remove(".test");//remove all p elements that has class .test
5. CSS
$(selector).addClass("Classname1 class2");
$(selector).removeClass("class");
$(selector).toggleClass("class"); //if active then remove &vv
$("p").css("background-color");//get background color
$(selector).css("propertyname","value"); //set css values
$(selector).css({"propertyname":"value","propertyname":"value",...});//set multiple css values
6. DIMENTIONS
$(selector).width(); //width of element exclude padding,margin,border ie $("div").width();
$(selector).height(); //height of element exclude padding,margin,border
$(selector).innerWidth(); // width includes padding
$(selector).innerHeight(); //height includes padding
$(selector).outerWidth(); //full width of element
$(selector).outerHeight(); //full height of element
$(document||window||"p").width();
7. Traversing:Ancestors, Descendants, Siblings,Filtering, Traversing methods
1. Ancestors: PARDADA
$(selector).parent(); //parent of element
$(selector).parents(); //all parents upto root html
$(selector).parentsUntil("body"); //current to body tag parents
$("selector").closest("ul").css({"color": "red", "border": "2px solid red"}); // jo phla bab, dada ya jo b find hwa,
ie
<div>
<tr>
<td>mogo</td>
<td><a href="123" class="123"></a></td>
</tr>
</div>
<script>
$(document).on('click', 'a', function (e) {
e.preventDefault(); // Prevent the default behavior of the anchor tag
$(this).closest('tr').remove(); // Remove the closest <tr> element
});
</script>
2. Descendants: AULAAD
$(selector).children(); //all direct childs only
$(selector).find(); //return all descendants ie $("div").find("*");
$(selector).contents(); //all direct childs only with comments also
$("div").children("p.first")
3. Siblings: That has same parent
$(selector).siblings(); //all siblings , ie siblings("p")
$(selector).next(); //one next sibling
$(selector).nextAll(); //all next siblings
$(selector).nextUntil("h2"); //current to h2 siblings
$(selector).prev(); //one previous siblings
$(selector).prevAll(); //all previous siblings
$(selector).prevUntil("h2"); //current to previous h2 sibling
4. Filtering: find elements using positions
$(selector).first(); // ie first("div"); find first div in document
$(selector).last(); // ie last("div"); find last div in document
$(selector).eq(n); //element with index n find ie $("div").eq(0) find first div in document
$(selector).filter("criteria"); //ie ("p").filter(".cl") //find all p elements that have class cl
$(selector).not("criteria"); //ie ("p").not(".cl") //find all p elements that have not class cl
5. Traversing methods:
$(selector).$("p").has("span"); //return all elements that have span element
$(selector).each(function(index,element));
$("li").each(function(){
alert($(this).text());
});
$(selector).slice(2); // select all elements but first 2 (0,1 index)
Check if p parent is div
if ($("p").parent().is("div"));
8. AJAX In JQuery
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.
1. load method $(selector).load(URL,data,callback);
The load() method loads data from a server and puts the returned data into the selected element.
$("#div1").load("demo_test.txt");
$("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: " + xhr.status + ": " + xhr.statusText);
});
});
2. HTTP Requests using Ajax
| 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. | 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. |
>> GET Method $.get(URL,callback);
$("button").click(function(){
$.get("demo_test.asp", function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
});
>> POST method
$("button").click(function(){
$.post("demo_test_post.asp",
{
name: "Donald Duck",
city: "Duckburg"
},
function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
});
9. JQuery Filter Table searches
<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>
https://www.w3schools.com/jquery/jquery_ref_ajax.asp
10. Jquery No Conflit
jQuery uses the $ sign as a shortcut for jQuery. There are many other popular JavaScript frameworks that use $ also.
The noConflict() method releases the hold on the $ shortcut identifier, so that other scripts can use it.
$.noConflict();
jQuery(document).ready(function(){
jQuery("button").click(function(){
jQuery("p").text("jQuery is still working!");
});
});
You can also create your own shortcut very easily. The noConflict() method returns a reference to jQuery, that you can save in a variable, for later use. Here is an example:
var jq = $.noConflict();
jq(document).ready(function(){
jq("button").click(function(){
jq("p").text("jQuery is still working!");
});
});
If you have a block of jQuery code which uses the $ shortcut and you do not want to change it all, you can pass the $ sign in as a parameter to the ready method.
$.noConflict();
jQuery(document).ready(function($){
$("button").click(function(){
$("p").text("jQuery is still working!");
});
});