Understanding jQuery in Just Few Minutes

ADMEC Multimedia Institute > Web Design > Understanding jQuery in Just Few Minutes

jQuery is the most popular JavaScript’s library in the world. It has tremendously simplified the way of coding in JavaScript for developers. In this post you will be reading about jQuery’s selectors, filters, effects, css, and event APIs. API stands for Application Programming Interface means we have to use very simple methods which are called API while they might contain very complex code structure in background.

I have put some importnat information in points, so please read carefully.

  • jQuery is a fast and concise JavaScript library created by John Resig in 2006. jQuery simplifies HTML document traversing, event handling, animating.
  • jQuery is a lightweight, “write less, do more”, JavaScript library.
  • The purpose of jQuery is to make it much easier to use JavaScript on your website.
  • jQuery takes a lot of common tasks that requires many lines of JavaScript code to accomplish, and wraps it into methods that you can call with a single line of code.
  • jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation.

The jQuery library contains the following features

  1. HTML/DOM manipulation
  2. CSS manipulation
  3. HTML event methods
  4. Effects and Animations
  5. Form Validation
  6. AJAX
  7. Utilities

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

Adding jQuery to Your Web Pages

To use jQuery, you need to download the jQuery library and include it on the pages you wish to use it.

The jQuery library is a single JavaScript file, and you reference to it using the HTML <script> tag:

<head>
     <script src="jquery.js"></script>
</head>

Notice that the <script> tag should be inside the page’s <head> section.

CDN link is the best way to improve the performance of the website.

<head> 
     <script src="https://code.jquery.com/jquery-latest.js"></script> 
</head>

There are two versions of jQuery available for downloading:

a) Production version – this is for your live website because it has been minified and compressed
b) Development version – this is for testing and development (uncompressed and readable code)

Both versions can be downloaded from jQuery.com.
Place the downloaded file in the same directory as the pages where you wish to use it.

If you don’t want to download and host jQuery yourself, you can include it from a CDN (Content Delivery Network).
Both Google and Microsoft host jQuery.

To use jQuery from Google, use one of the following:

Google CDN:

<head> 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"> </script> 
</head>

jQuery Syntax

The jQuery syntax is tailor made for selecting HTML elements and perform some action on the element(s).

Basic syntax is:

$(selector).action()

A $ sign to define/access jQuery
A (selector) to “query (or find)” HTML elements
A jQuery action() to be performed on the element(s)

Examples:

$(this).hide() - hides the current element
$("p").hide() - hides all <p> elements
$(".test").hide() - hides all elements with class="test"
$("#test").hide() - hides the element with id="test"

jQuery Selectors

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

With jQuery selectors you can find elements based on their id, classes, types, attributes, values of attributes and much more. It’s based on the existing CSS Selectors, and in addition, it has some own custom selectors.

All type of selectors in jQuery, start with the dollar sign and parentheses: $().

The element Selector

The jQuery element selector selects elements based on their tag names.

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

$("p") ;

Example

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

$(document).ready(function(){
     $("button").click(function(){
          $("p").hide();
     });
});

The #id Selector

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

An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.
To find an element with a specific id, write a hash character, followed by the id of the element:

$("#test")

Example

When a user clicks on a button, the element with id=”test” will be hidden:

$(document).ready(function(){   
    $("button").click(function(){
        $("#test").hide();
    });
});  

The .class Selector

The jQuery class selector finds elements with a specific class.
To find elements with a specific class, write a period character, followed by the name of the class:

$(".test")

Example

When a user clicks on a button, the elements with class=”test” will be hidden:

$(document).ready(function(){
    $("button").click(function(){   
        $(".test").hide();
    });
});

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
$("tr:not('tr.abc')"); // Selects all <tr> elements except those have 'abc' class attached to

jQuery Event Methods

Event handlers are methods that are called when “something happens” in HTML.

The term “triggered (or “fired”) by an event” is often used.

It is common to put jQuery code into event handler methods in the <head> section.

In the example below, a function is called when the click event for the button is triggered:

Example

<!DOCTYPE html>
<html>
<head>
<script src="jquery.js"></script>
<script>
     $(document).ready(function(){   
          $("button").click(function(){  
               $("p").hide();
          });
     });
 </script>
</head>  
<body>
     <h2>This is a heading</h2>
     <p>This is a paragraph.</p>
     <p>This is another paragraph.</p>
     <button>Click me</button>
</body>
</html> 

Some jQuery Event Methods

Here are some examples of event methods in jQuery:

Event Methods and Descriptions

$(document).ready(function);
// Specifies a function to execute when the DOM is fully loaded

$(selector).click(function);
// Binds/Triggers the click event

$(selector).dblclick(function);
// Binds/Triggers the double click event

$(selector).focus(function);
// Binds/Triggers the focus event

$(selector).mouseover(function)
// Binds/Triggers the mouseover event

$(selector).on();
//bind any event

$(selector).off();
//unbinds any previously bind event

$(selector).delegate();
//binds and add custom event

$(selector).undelegate();
//unbinds any event

$(selector).hover();
//works for mouse over and mouse out

$(selector).one();
//bind an event to element(s) for one time use only

jQuery Effects

Effects are the charm of jQuery. They are very simple to use. There are main 4 types of effects APIs are in jQuery and they are Basics, Fading, Sliding, and Custom.

jQuery hide() and show()

With jQuery, you can hide and show HTML elements with the hide() and show() methods:

Example

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

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

Syntax:

$(selector).hide(speed,callback);
$(selector).show(speed,callback);

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

The optional callback parameter is the name of a function to be executed after hide (or show) completes.

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

Example

$("button").click(function(){  
    $("p").hide(1000);
});

jQuery toggle()

With jQuery, you can toggle between the hide() and show() methods with the toggle() method.

Example

$("button").click(function(){
    $("p").toggle();
}); 

Syntax:

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

The optional speed parameter can take the following values: “slow”, “fast”, or milliseconds.

The optional callback parameter is the name of a function to be executed after the toggle() method completes.

jQuery Effects – Fading

With jQuery you can fade an element in and out of visibility.

jQuery has the following fade methods:

  • fadeIn()
  • fadeOut()
  • fadeToggle()
  • fadeTo()

jQuery fadeIn() Method:

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

Syntax:

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

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

The optional callback parameter is the name of a function to be executed after the fading completes.

The following example demonstrates the fadeIn() method with different parameters:

Example

$("button").click(function(){
    $("#div1").fadeIn();
    $("#div2").fadeIn("slow");
    $("#div3").fadeIn(3000);
});

jQuery fadeOut() Method:

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

Syntax:

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

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

The optional callback parameter is the name of a function to be executed after the fading completes.

The following example demonstrates the fadeOut() method with different parameters:

Example

$("button").click(function(){
    $("#div1").fadeOut();
    $("#div2").fadeOut("slow");
    $("#div3").fadeOut(3000);
});

jQuery fadeToggle() Method:

The jQuery fadeToggle() method toggles between the fadeIn() and fadeOut() methods.

If the elements are faded out, fadeToggle() will fade them in.

If the elements are faded in, fadeToggle() will fade them out.

Syntax:

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

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

The optional callback parameter is the name of a function to be executed after the fading completes.

The following example demonstrates the fadeToggle() method with different parameters:

Example

$("button").click(function(){
     $("#div1").fadeToggle();
     $("#div2").fadeToggle("slow");
     $("#div3").fadeToggle(3000);
});

jQuery fadeTo() Method:

The jQuery fadeTo() method allows fading to a given opacity (value between 0 and 1).

Syntax:

$(selector).fadeTo(speed,opacity,callback);

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

The required opacity parameter in the fadeTo() method specifies fading to a given opacity (value between 0 and 1).

The following example demonstrates the fadeTo() method with different parameters:

Example

$("button").click(function(){
    $("#div1").fadeTo("slow",0.15);
    $("#div2").fadeTo("slow",0.4);
    $("#div3").fadeTo("slow",0.7);
});

jQuery Effects -Sliding

The jQuery slide methods slides elements up and down.

Click to slide down/up the panel

jQuery Sliding Methods:

With jQuery you can create a sliding effect on elements.

jQuery has the following slide methods:

  • slideDown()
  • slideUp()
  • slideToggle()

jQuery slideDown() Method:

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

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

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

The optional callback parameter is the name of a function to be executed after the sliding completes.

The following example demonstrates the slideDown() method:

Example

$("#flip").click(function(){
    $("#panel").slideDown();
});

jQuery slideUp() Method:

The jQuery slideUp() method is used to slide up an element.

Syntax:

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

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

The optional callback parameter is the name of a function to be executed after the sliding completes.

The following example demonstrates the slideUp() method:

Example

$("#flip").click(function(){
    $("#panel").slideUp();
});

jQuery slideToggle() Method:

The jQuery slideToggle() method toggles between the slideDown() and slideUp() methods.

If the elements are slide down, slideToggle() will slide them up.

If the elements are slide up, slideToggle() will slide them down.

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

The optional speed parameter can take the following values: “slow”, “fast”, milliseconds.

The optional callback parameter is the name of a function to be executed after the sliding completes.

The following example demonstrates the slideToggle() method:

Example

$("#flip").click(function(){
    $("#panel").slideToggle();
});

jQuery CSS API

It is impossible to ignore CSS APIs when you are talking about jQuery. jQuery offers various methods to deal with CSS.

addClass(); //adds class to any set of matched elements

removeClass(); //remove class from any set of matched elements

hasClass(); //checks for the class to any set of matched elements

toggleClass(); //add or remove one or more classes from each element in the set of matched elements

css(); //adds css properties as inline to any set of matched elements

Example:

$('p').addClass('class'); //adding a class to paragraph(s)

$('p').addClass('class1 class2'); //adding multiple classes to paragraph(s)

$('p').css('color', 'red'); //changing single property of paragraph(s)

$('p').css({'color': 'red', 'border':'2px solid green'}); //changing multiple properties of paragraph(s)

jQuery Ajax API

I hope you are aware of Ajax term already. It is a technique to fetch data from the server using JavaScript and XML (any database) so jQuery also offers great and capable APIs to deal with Ajax. Some common methods are:

  • $.ajax();
  • $.ajaxComplete();
  • $.ajaxError();
  • $.ajaxSuccess();
  • $.getJSON();

Example 1: A very basic Ajax request using jQuery.

$.ajax({
    url: 'myfile.php',
    cache: false;
    success: function(html){
        alert(html);
    }
});

In above example myfile.php will return a result either from the database or a plain string written in this page to the success callback function. This callback function will accept the value in ‘html’ argument and later can be used in jQuery.

Example 2: Parametric ajax request with method post.

$.ajax({
    url: 'myfile.php',
    cache: false;
    method: post,
    data: {'name':'product1', 'price':'250'},
    success: function(html){
        alert(html);
    }
});

Example 3: Parametric ajax request with method post and ‘done’ callback instead ‘success’.

$.ajax({
  method: "POST",
  url: "some.php",
  data: { name: "John", location: "Boston" }
}).done(function( msg ) {
    alert( "Data Saved: " + msg );
});

Summary

jQuery is drastically an easy and sophisticated way to reduce the JavaScript code for web pages. If we look at other side of jQuery, its simplicity becomes difficulty for beginners. Our institute provides training by the master of jQuery and they will give you confidence to code and create anything that you want.


View full presentation on slideshare:

Design patterns in JavaScript, jQuery, Angular

12 Famous Typographers to Inspire You from Ravi Bhadauria

Design patterns in JavaScript, jQuery, Angular from ADMEC Multimedia Institute

Related Posts

Leave a Reply

Call Now