Post

JQuery

Introduction

jQuery is a JavaScript library created by John Resig in 2006 with an objectives Write less, do more. The main features of jQuery are event handling, Ajax interactions, animations, traversing, DOM manipulation, Cross Browser Support, etc.

jQuery Syntax

$(selector).action()

Here $ sign is used to define jQuery, a selector is used to find HTML DOM elements and an action is jQuery function to be performed on the HTML elements.

`$(this).hide()` // To hide current element use
`$("h1").hide()` // To hide all h1 elements use
`$("#myDiv").hide()` // To hide element with id "myDiv" use
`$(".myDiv").hide()` // To hide element with class "myDiv" use

jQuery event should call inside $(document).ready() function in order to work on HTML page and script inside this function will exectuted before loaded the page contents and when DOM is loaded.

$(document).ready(function() {
   // The script written here will execute when DOM is ready
});

Example Usage

<html>
    <head>
        <title>jQuery Example</title>
        <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
        </script>
        <script type="text/javascript">
            $(document).ready(function() {
                $("#header").click(function() {
                    alert("jQuery triggered");
                });
            });
        </script>
    </head>

    <body>
      <div id="header">
        Click Me
      </div>
    </body>
</html>

Steps to install jQuery

jQuery can be installed in two ways:

  1. Download jQuery library in your system and include in HTML code.
    • Download latest version of jQuery into your project directory from https://jquery.com/download/

    Here is the example code

<html>
    <head>
        <title>jQuery</title>
        <script type="text/javascript" src="/js/jquery-3.4.1.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                console.log("Hello jQuery");
                document.write("Hello jQuery");
            });
        </script>
    </head>
    <body>
        <p>jQuery</p>
    </body>
</html>
  1. Include jQuery library in your HTML code from Content Delivery Network (CDN).

Here is the example code

<html>
    <head>
        <title>jQuery</title>
        <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
      </script>
        <script type="text/javascript">
            $(document).ready(function() {
                console.log("Hello jQuery");
                document.write("Hello jQuery");
            });
        </script>
    </head>
    <body>
        <p>jQuery</p>
    </body>
</html>

jQuery Selectors

jQuery Selectors are used to select HTML elements based on their name, id, classes, types, attributes, values to perform various tasks.

jQuery selectors start with the factory function which starts with dollar sign followed by parentheses $() which is synonym of jQuery(). Sometime conflict occurs with $ sign when using other JavaScript library in that case use jQuery() instead of $() to avoid conflict.

Here are few lists of jQuery selectors

Selector
$(“*”) # Selects all element
$(this) # Selects current element
$(“#myDivId”) # Selects an element with an Id=”myDivId”
$(“#myDivClass”) # Selects an element with class=”myDivId”
$(“p”) # Selects all paragraph element matched by <p>
$(“p > *”) # Selects all elements that are children of paragraph element
$(“p.myDivClass”) # Select all paragraph elements having class=”myDivClass”
$(“p:first”) # Select first paragraph element
$(“ul li:first”) # Select first <li> element of the first <ul>
$(“ul li:first-child”) # Select first <li> element of every <ul>
$(“#myDiv p”) # Select <p> elements under div element with id=”myDiv”
$(“li > ul”) # Select all <ul> elements which are children of <li> elements
$(“p a.myClass”) # Select all links or elements having class=”myClass” which is children of <p> elements
$(“a#myId.myClass”) # Selects links with an id=”myId” and class=”myClass”
$(“li:not(.myclass”) # Selects all elements matched by <li> which do not have class=”myclass”
$(“[href]”) # Selects all elements with an href attribute
$(“a[target=’_blank’]”) # Selects all elements with a target attribute value equal to “_blank”
$(“a[target!=’_blank’]”) # Selects all 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
$(“strong + em”) # Selects all elements matched by which is followed by
$(“p ~ ul”) # Selects all elements matched by <ul> which is followed by <p>
$(“code, em, strong”) # Selects all elements which is matched by or or
$(“p strong, .myDivClass”) # Select all strong elements which are followed by <p> and having class=”myDivClass”
$(“:empty”) # Select all elements having no children
$(“p:empty”) # Select all paragraph elements having no children
$(“div[p]”) # Select all elements having <div> which contains <p>
$(“p[.myDivClass]”) # Select all paragraph elements having class=”myDivClass”
$(“:radio”) # Selects all the radio buttons in the form
$(“:checked”) # Selects all the checkbox in the form
$(“:input”) # Selects input element of the form like: input, textarea, select, button, etc
$(“:text”) # Selects all input text elements
$(“p:lt(3)”) # Selects all first three elements
$(“p:gt(2)”) # Selects all paragraph elements excluding first two or after third one
$(“div/p”) # Selects all paragraph elements which are under div tag
$(“div//code”) # Selects all elements which are descendants of <div>
$(“//p//a”) # Selects all links that are descendants of paragraph
$(“:parent”) # Selects all elements which are parent of another element, including text
$(“li:contains(second)”) # Selects all elements matched by <li> that contain the text second

jQuery attributes

Some jQuery methods used to get or set the value of attributes, property, html, etc are postulated below:

attr() - get or set the specified attribute of the target element. prop() - get or set the specified property of the target element. html() - get or set the html content to the specified target element. val() - get or set the value of the specified target element. text() - get or set the text for the specified target element.

jQuery attributes are almost uses with properties like className, id, tagName, href, title, src, rel. HTML tags are the h1, h2, p, img, div, head, body, bold(b), anchor(a), form, hr, br, input, li, ul, ol, link, option, strong, small, table, td, tr, th, u, tt, center, etc.

jQuery attr() methods

attr() is used to get value of attributes and attr(name, value) is used to set the attribute with new value which will apply to all elements.

<!DOCTYPE html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js">
        </script>
        <script>
            $(document).ready(function () {     
                alert($("div").attr("style")); // Select div tag and get the value of style attributes
                $("p").attr("class", "greenColorStyle"); // all paragraph tag's class will update to greenColorStyle
                var title = $("p").attr("title"); // get value of paragraph's attributes title
                $("#progTitle").text(title); // inspect div id progTitle and replace text defined by variable title
            });
        </script>
    <style type="text/css">
        .greenColorStyle {
        color: green;
        }
    </style>
    </head>
    <body>
    <div style="color: red; ">This is a paragraph under div</div>
    <p title="Programming Tutorials">Get value of title attributes and replace div having id progTitle</p>
    <div>
        <p>After page loads all paragraph should be in green color</p>
        <p>Another text</p>
    </div>
    <div id="progTitle"></div>
    </body>
</html>

addClass(className)

addClass(className) is used to apply defined styles to selected elements.

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js">
        </script>
        <script>
            $(document).ready(function () {     
            $("#myDiv").addClass("greenColorStyle");
            });
        </script>
    <style type="text/css">
        .greenColorStyle {
        color: green;
        }
    </style>
    </head>
    <body>
    <div id="myDiv">This is a paragraph under div</div>
    </body>
</html>

Some more attr methods are:

  • removeAttr() Removes an attribute of matched elements
  • removeClass(class) Removes the class of matched elements
  • hasClass(class) check if class present then returns true
  • toggleClass(class) add the class if absent and remove the class if present
  • html() Get the html contents of an element
  • html(val) set the html content with value of element
  • text() get the combined text contents of elements
  • text(val) set the text content of element
  • val() get input value of first matched element
  • val(val) set the value attribute of every matched element

jQuery Traversing

jQuery traversing is used to find html elements based on their relation to other elements. jQuery traversing means to move over elements to find a particular or entire element.

Here are some list of jQuery traversing methods:

  • add() Collects one or more matched elements which are passed inside the method to create an object which can be manipulated at the same time.
<html>
<head>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js">
	</script>
	<script>
		$(document).ready(function () {     
		  var jqObj = $('div').add('p').add('span').css( "background", "yellow" );
		  jqObj.addClass('greenColorStyle');
		});
	</script>
   <style type="text/css">
  	.greenColorStyle {
      color: green;
    }
   </style>
</head>
<body>
  <div id="myDiv" style="text-align: center; padding: 20px">This is a paragraph under div</div>
  <p>Some more text</p>
</body>
</html>
  • addBack() adds the previous set of elements with current set and maintains them in a stack which can be manipulated.
# add together paragraph tags with myDiv div tag and implement bgGreen color to both
$("div.myDiv").find("p").addBack().addClass("bgGreen");
  • not() get all elements which do not match specific selector

Tree Traversing

Descendants
  • children

Get all the child elements of the selected element.

$(selector).children();
  • find()

Get all the specified child elements of each selected element.

Ancestors
  • closest find the first ancestor of the selected selector.
$(selector).closest(selector or element);
  • parent

get the parent element of specified selector

$(selector).parent();
  • parents

get all ancestor elements of specified selector

$(selector).parents();
  • parentsUntil()

get all ancestor elements between specified selector and arguments.

$(selector).parentsUntil(selector, element)
  • offsetParent()

get the first parent element of specified selector.

Siblings
  • siblings

get all siblings of the specified selector.

$(selector).siblings()
  • next()

get next sibling element of the specified selector.

$(selector).next()
  • nextAll()

get all next sibling elements of the specified selector.

$(selector).nextAll()
  • nextUntil()

get all next sibling between specified selector and arguments.

$(selector).nextUntil()
  • prev()

get the previous sibling element of the specified selector.

$(selector).prev(selector)
  • prevAll()

get all the previous siblings of specified selector.

$(selector).prevAll(selector, filter_element)
  • prevUntil()

get all the previous siblings between specified selector and arguments.

$(selector).prevUntil(selector, filter_element)
filtering
  • first()

get the first element of the specified selector

  • last()

get the last element of the specified selector

  • eq()

get the element with specified index number of the specified selector.

$(selector).eq(index)
  • filter()

remove or get the element which are matched with specified selector

$(selector).is(selector or function or elements)
  • has()

get all elements which have one or more elements within and are matched with specified selector.

$(selector).has(selector)
  • is()

it checks if one of the specified selector is matched with arguments.

.is(selector or function or elements)
  • map()

traverse arrays and objects and results a new array

1
2
3
jQuery.map(array, function(val, i) {
    // do stuff here
});
  • slice(start, end)

get the subset of specified selector based on it’s argument index or start and stop value.

$(selector).slice(start, end)

jQuery Effects

jQuery helps us to add various types of visual effects on our webpage.

jQuery effects are listed below:

Display Effects Sliding Effects Fading Effects Other Effects
show() slideUp() fadeIn() delay()
hide() slideDown() fadeOut() animate()
toggle() slideToggle() fadeToggle() fadeTo()
    fadeTo()  

Here are the description of some jQuery effect methods:

show()

Display the selected elements

Usage:

$("#btn-hide").click(function() {
    $("p").hide()
});
$("#btn-show").click(function() {
    $("p").show()
});

hide()

Hide the selected elements

toggle()

This function is used to show to hide (toggle) the matched elements

Usage:

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

slideUp()

This function is used to display the slideup effects which first hide the element and then show the element with sliding effects once it is completed execute the callback function, thus this function is used to slide up an element.

Syntax

$(selector).slideUp(speed,callback);
  • speed - valid speed values are slow, normal, fast
  • callback - which is optional parameter and this function is called once the animation is completed.

Usage

$("#btnUp").click(function(){
    $(".target").slideUp('slow', function(){ 
        $("#div-id").text('Slide Up Effect');
    });
});

slideDown()

This function is used to slide down the element.

Syntax

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

Usage

$("#btnDown").click(function(){
    $(".target").slideDown( 'slow', function(){ 
        $("#div2-id").text('Slide Down Effect');
    });
});

slideToggle()

slideToggle() method is used to toggle between slideUp() and slideDown() which means if the element if slide down this function helps them slide up and vice versa.

Syntax:

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

fadeIn()

This function is used to show fades in effect from the hidden element to make it visible.

$(selector).fadeIn(speed,easing,callback)
  • speed - valid speed values are slow, normal, fast
  • callback - which is optional parameter and this function is called once the animation is completed.
  • easing - This is optional. This feature shows the effect in various speed in various dimension. Various options are:
    • swing - moves faster in the middle dimension and slower at the start or end.
    • linear - moves in constant speed.

fadeOut()

This function is used to show fades out effect from the visible element to make it hidden.

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

fadeToggle()

This method is used to toggle between fadeIn() and fadeOut() which will fades in the element if it is fades out and vice versa.

Syntax

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

fadeTo()

This method is used to show the fading effect of an element partially in or out to make it transparent.

Syntax

$(selector).fadeTo(speed,opacity,callback);
  • speed - valid speed values are slow, fast, or milliseconds

  • opacity - The values of opacity are between 0 and 1 0 - fully transparent (hidden) 1- fully opaque (shown)

  • callback - which is optional parameter and this function is called once the animation is completed.

delay()

The delay() is an inbuilt method in jQuery which is used to set a timer to delay the execution of the next item in the queue.

Syntax

$(selector).delay(speed,queueName)

The paremeters used are explained here:

  • speed - The values are milliseconds, “slow”, “fast”
  • queueName - The default value if “fx” and you can set the queue name here and is the optional parameter.

Usage

$("#mybtn").click(function() {
    $("#slow-delay-div").delay("slow").fadeIn();
    $("#fast-delay-div").delay("fast").fadeIn();
    $("#ms-div").delay(1000).fadeIn();
});

animate()

This method is used to create custom animations which gives special effects using style properties of the element. Specify the selector to get the reference of an element and call animate() to apply animation, this animate() function takes json object for style properties, speed of animation, and other options.

Syntax

$(selector).animate({ params },speed, callback);
$(selector).animate({ stylePropertyName: 'value', duration, easing, callback }, { options })

Usage

<!DOCTYPE html>
<html>
<head>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js">
    </script>
    <script>
        $(document).ready(function () {
			$('#animateEx').animate({
                        height: '50px',
                        width: '50px'
                    });
			});
    </script>
	<style>
        .green {
            background-color: green;
            height: 350px;
            width: 350px;
        }
    </style>
</head>
<body>
	<h1>Here is an example of jQuery animate()</h1>

	<div id="animateEx" class="green">
	</div>
</body>
</html>

This post is licensed under CC BY 4.0 by the author.