jQuery Basics

What is jQuery ?

 
jQuery is a JavaScript library that we can include in our webpage.

It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers.
 
With jQuery, we can do the following :
 

1 : Find elements using CSS style selectors

 
jQuery provides a function called jQuery() that we can use to find or select elements.
 
For example, the following code selects all ‘div’ elements :


jQuery('div')

 
The sybmol $ is used as a shorthand for jQuery. So, the above code can also be written as :


$('div')

 

2 : Do something with the html elements using the jQuery methods

 
jQuery provides several methods that we can use to do some operation with the html elements.
 
For example, the following code will hide all the “div” elements on the page.


 $("div").hide();

 

Simple jQuery Example

 
In order to use jQuery, first we need include the jQuery script on our page.
 
We can download the jQuery file from http://jquery.org or we can include the link from a CDN like Google or Microsoft. The example below refers to the jQuery script from Google’s CDN.
 
In this example, we will hide the div element when “Click me” button is clicked.
 
jQuery example
 

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("div").hide();
    });
});
</script>
</head>
<body>
<div>This is a div</div>
<p>This is a paragraph</p>
 
<button>Click me</button>
</body>
</html>


 
This example creates a div and a paragraph element.
 
Ignore the $(document).ready() for now as we will see more on that in the next article.
 
The script inside it hides all “div” elements when the button is clicked.


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

 
Here is how the result page looks.. click on the button to hide the div element.
 

 

Why use jQuery ?

 
We can achieve the same functionality in JavaScript that we want to perform in jQuery.
 
But jQuery provides the following advantages :
 

  1. With jQuery, we can achieve the same task as JavaScript with fewer lines of code. It makes coding simpler.
  2.  

  3. With JavaScript, we run into many cross-browser compatibility issues. But jQuery automatically handles the inconsistent ways in which different browsers select elements and handle any events. So, we don’t have to write cross-browser fallback code.
  4.  

  5. jQuery provides CSS style selectors for selecting elements. This often requires less code to select elements and is often faster compared to old DOM methods.

 

You may also like :

 

© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

You may also like...

Leave a Reply.. code can be added in <code> </code> tags