CommonLounge Archive

jQuery: Introduction

September 26, 2018

What is jQuery?

jQuery is an open source JavaScript library or module, which basically means that it is a JavaScript file that has been written by someone else to make our tasks concise and easy. jQuery was made to make HTML—JavaScript interaction easier, it has a lot of stuff related to event handling and animations built in.

It is not a new programming language; it is just a set of functions and properties written in JavaScript.

Why jQuery?

  • jQuery is cross-browser compatible. This means that when you run your code, the output will remain the same, independent of the browser. It won’t change from one browser to another.
  • jQuery has a shorter “syntax” than JavaScript, which means to get the same result you’ll have to write lesser code if you use jQuery. for e.g.,
JavaScript:
document.getElementById("ptag").innerHTML = "Inside ptag! <br>";
jQuery:
$("#ptag").html("Inside ptag! <br>");
  • It has huge community support because it is used in a large number of websites. If you encounter any error, you’ll surely find a solution in the community forums.
  • It is very well documented, including code examples, etc.

Using jQuery

jQuery is a JavaScript library which means it is a JavaScript file. You can any include an external JavaScript file in your HTML page using the script tag:

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

In the above example, the jquery.js file is located inside a folder called js. The src attribute can be used to import an external JavaScript file instead of writing code inside the script tags.

The jQuery file is provided in a minified version as well in which all the whitespaces are removed, function names are replaced with single characters etc., so as to reduce the file size. The minified current version 3.3.1 is about 87 KBs in size whereas the normal version is about 272 KBs. These sizes may not sound like much but they can really affect the loading time of a website.

The above method uses a locally stored JavaScript file. There’s another and the more popular way which is using CDNs. CDN stands for Content Distribution Network.

A CDN is a geographically distributed network of proxy servers and their data centers. The goal is to distribute service spatially relative to end-users to provide high availability and high performance.

The official website of jQuery provides a list of CDNs which can be used to import jQuery. The method is similar to the first one but instead of a locally stored file we use the file provided by the CDN. For example, to use Google’s jQuery CDN:

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

The $ sign

jQuery is represented and called using the jQuery() method. There’s also a shorthand for that, the $ sign.

$("#ptag");
jQuery("#ptag");

The above two lines are equivalent. The $ sign is used more widely.

We have already discussed what the Document Object Model or DOM is. It is a tree like structure in which every html element is represented by a node. Elements contained inside another HTML element are the container element’s child nodes.

The outermost layer of the DOM is called the document object. To begin writing jQuery code we make sure that the document is ready.

$(document).ready(function() {
    // do something
});

This will run the function inside the ready method when the document has finished loading. This function is actually a callback function which is called when document is ready. The code becomes very readable if you write it in jQuery. Again, we are using the words “..write it in jQuery..”, but this doesn’t imply that it’s another programming language.

All your jQuery code should be wrapped inside the function called on $(document).ready(). This is because jQuery is used to interact with DOM elements and executing code that interacts with elements that have not been loaded yet doesn’t make sense. It is considered to be the best practice to write all your custom jQuery code inside the ready method as well.

Selecting objects using different identifiers

jQuery uses CSS syntax to get references to nodes in the DOM tree. For using id we add a prefix #, for class the prefix is . and for selecting elements using tag name, you just pass the tag name. Let’s look at examples of each:

<p id="ptag">
    ...
    ...
    Some random text
</p>
<button class="btn"> Click Me! </button>
<b>This text is bold</b>
<script src="jquery.js"></script>
<script>
    $("#ptag"); // gives a reference to the element with id "ptag"
    $(".btn");  // gives an array of elements with class "btn"
    $("b");     // gives an array of <b> tag elements
</script>

You can also select elements with any of their other attributes! For example:

<p name="paragraph">
    This is another paragraph with random text
</p>

To select this we can write:

$("p[name='paragraph']");

We can use any attribute of the tag and use it in the following structure

$("tagName[attributeName='attributeValue']");

For your reference, there’s a list of selectors in jQuery at the end of this tutorial.

jQuery methods

A basic jQuery example follows this format

$("selector").method(callbackfunction);

The callback function may or may not be there depending on the method we are using.

Create a new HTML file called jquery.html and write the following code in it. We are using Google’s CDN for the jquery library.

<html>
    <head>
        <title>jQuery</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    </head>
    <body>
        <p id="paragraph">
        </p>
        <script>
            function changeHTML() {
                $("#paragraph").html("Hello World!");
            }
            $(document).ready(changeHTML);
        </script>
    </body>
</html>

We created a function changeHTML() which changes the text inside the element with id "paragraph". We then passed it inside the ready method as a callback method. The changeHTML() function uses the jQuery method .html() which is similar to the innerHTML property in plain JavaScript.

$("#paragraph").html("Hello World!");
document.getElementById("paragraph").innerHTML = "Hello World!";

The above two lines are do the same thing.

We can also replace the above script with:

$(document).ready(function() {
    $("#paragraph").html("Hello World!");
});

jQuery Events

In the code we’ve written, the function executes as soon as the document gets ready, and there was no user interaction. The ready method is basically an event in this case. As soon as the event is triggered the callback function is called.

This is an example of an event triggered without user interaction. There could be other events as well which can be triggered by the user, for example, clicking a button, typing in a text field etc.

Let’s create a button and do something when it is clicked.

<button id="clickme"> Click me </button>
<br>
<p id="paragraph2">
</p>
<br>
<script>
    function filltext() {
        $("#paragraph2").html("This is paragraph number 2. <br>");
    }
    $(document).ready(function() {
        $("#clickme").click(filltext);
    });
</script>

We have used the click() method to call the function filltext(). The click event is triggered whenever the user presses the button. When the event is triggered the function passed as callback (filltext, in this case) is called.

Let’s create a text input field and change the content inside #paragraph2 as and when the text in the input field changes.

...
<input type="text" id="textinput">
<script>
function getval() {
    $("#paragraph2").html($("#textinput").val());
}
$(document).ready(function() {
    ...
    $("#textinput").keyup(getval);
});
...
</script>

The three dots … represents other code that we might have previously written; just a convention.

We have used the keyup() method here. It gets triggered as soon as a pressed key is released. It calls the function passed as the callback here which is getval().

Some other events that are most commonly used are:

  • hover() - Hover: executes when the mouse is hovered over an element.
  • mouseenter() and mouseleave(): Mouse entering or leaving an element, respectively.
  • submit() - Submit: executes when a form is submitted.
  • scroll() - Scroll: executes when the screen is scrolled.
  • keydown() - Keydown: executes when you press down on a key on the keyboard.

jQuery effects

jQuery has a lot of animation effects functions built into it, so that you don’t have to write a lot of JavaScript to show animations. The effects are generally used along with events. Let’s write a paragraph and create a button which will slide the paragraph element up if it is visible else it will slide it down.

We will use the slideToggle() animation method which toggles the visibility and slides the element up or down. Change your HTML to the following:

<html>
    <head>
        <title>jQuery</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    </head>
    <body>
        <p id="paragraph" style="background: lightblue; width: 200px;">
            Hello this is a paragraph. <br>
            This element is the p tag <br>
            It is used to define a paragraph <br>
            Done!
            <br>
        </p>
        <button id="slidetogglebutton">
            Click to toggle
        </button>
        <script>
        </script>
    </body>
</html>

We have made the p element’s background light blue and set the width to 200 pixels.

Inside the script tag at the end, add the following:

$(document).ready(function() {        // document is ready
    $("#slidetogglebutton").click(function() {   // on clicking the button
        $("#paragraph").slideToggle(); // call jQuery slideToggle()
    });
});

Now open the HTML file in a browser and you should see the paragraph element sliding up and down. There’s also another toggle function called fadeToggle() which fades in and out the element. Try changing slideToggle to fadeToggle in the script.

There are separate functions slideUp, slideDown, fadeIn and fadeOut for sliding up and down and fading in and out as well.

You can also animate individual CSS style properties using the animate() method. Change the script to the following and see what changes:

$(document).ready(function() {       
    $("#slidetogglebutton").click(function() {   
        $("#paragraph").animate({'margin-left': '200px'}); 
    });
});

This will move the element 200 pixels to the right because we have set the margin-left property to 200 pixels. You can read more about animate() here.

Appendix: List of selectors in jQuery

  • $("*") - Wildcard: selects every element on the page.
  • $(this) - Current: selects the current element being operated on within a function.
  • $("p") - Tag: selects every instance of the tag.
  • $(".example") - Class: selects every element that has the example class applied to it.
  • $("#example") - Id: selects a single instance of the unique example id.
  • $("[attr='value']") - Attribute: selects any element with attr attribute having value value.

© 2016-2022. All rights reserved.