Open In App

How to use jQuery library and call functions from it ?

Last Updated : 08 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see how we can include the jQuery library in the code & use the different call functions. We will be adding some animation effects to see its uses. jQuery is a lightweight JavaScript library that was built to simplify complex JavaScript tasks by generalizing various concepts into methods, that take multiple lines of code in a pure JavaScript program. The library is proficient in handling everything JavaScript can, such as DOM manipulation, Event Handling, AJAX, Animations and Effects, CSS Manipulation, Web APIs, etc. jQuery also takes care of cross-browser issues so that the code works exactly the same in all browsers.

Including jQuery in the Project: To include jQuery in our web application code, we can use 2 methods:

  • Include a CDN link. 
  • Include jQuery code in a JavaScript file.

We will understand both approaches to implementing jQuery & will understand it through the examples.

Including a jQuery CDN link: A CDN stands for Content Delivery Network. Its concept is simple, a copy of a file is stored on various servers all around the world. When a user wants to access this file, he accesses it from the server closest to his location. This provides a fast connection and a better backup.

Syntax:

<!DOCTYPE html>
<html>
<head>
    <title>Including jQuery into our Project</title>
</head>
<body>
<h2>Welcome To GFG</h2>
<p>Simply add the script tag at the end of body</p>
 
 <script src=
"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js" 
         integrity=
"sha512-STof4xm1wgkfm7heWqFJVn58Hm3EtS31XFaagaa8VMReCXAkQnJZ+jEy8PCC/iT18dFy95WcExNHFTqLyp72eQ==" 
         crossorigin="anonymous" 
         referrerpolicy="no-referrer">
</script>

</body>

</html>

Including the jQuery Source File: If you do not want to use a CDN link, you can simply download the source code into your repository. A single JS file is downloaded. Visit the jQuery website and download the file from there. Save the file into your project folder and link your HTML to it using the script tag. If you click on the uncompressed version link provided on the website, a file will be opened in the browser where all the source code of JQuery is available. Just copy it and paste it into a blank JS file in your project folder.

Syntax:

<!DOCTYPE html>
<html>
<head>
    <title>Including jQuery into our Project</title>
</head>
<body>
    <h2>Welcome To GFG</h2>
    <p>Include the local js file of jQuery code into your project</p>

    <script src="./main.js"></script>
    <script src="./jquery.js"></script>
</body>

</html>

Using jQuery Methods:

  • Calling jQuery Methods and Manipulating DOM: Now we will write a simple code to demonstrate how we execute jQuery methods. In jQuery, the document.querySelector() method of JavaScript is replaced by $(). This is the first step of jQuery reducing code to write. Once we have selected a DOM element, we can chain various methods on it that manipulate CSS and even add events and event listeners.

Syntax:

$(CSS_selector).method_to_manipulate_property("value_of_property");

Approach:

  • We create a simple HTML file, we add two h1 tags and two p tags. 
  • Add 3 buttons that will perform various DOM actions each having an id attribute. 
  • Select the target buttons with jQuery’s DOM selector – $(”). 
  • Then we chain the on() method, which is a general event listener of jQuery, on the selected element. 
  • We can also use a specific event listener, such as click(), which is triggered only when the user clicks that element. 
  • The first argument of the on() method is the event to which we want to listen, and the second argument is a function. 
  • In this function, we select the entire body and chain the css() method on it. This takes two arguments, the first is the CSS property we want to change, and the second argument is the new value of that property. 
  • Similarly, we use the text() method on the selected element to change the text of a DOM element. 
  • We also have addClass(), removeClass(), and toggleClass() to add, remove, and toggle classes of the selected element.

Example 1: This example illustrates the basic use of the jQuery library for calling the functions by using the jQuery CDN link.

  • index.html

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta name="viewport" 
          content="width=device-width, 
                   initial-scale=1.0">
    <script src=
            integrity=
"sha512-STof4xm1wgkfm7heWqFJVn58Hm3EtS31XFaagaa8VMReCXAkQnJZ+jEy8PCC/iT18dFy95WcExNHFTqLyp72eQ==" 
            crossorigin="anonymous" 
            referrerpolicy="no-referrer">
    </script>
  
    <style>
        .bigger{
            font-family: Arial, Helvetica, sans-serif;
            font-size: 20px;
            font-weight: bolder;
        }
    </style>
</head>
  
<body>
    <button id="body-color-changer">
        Change Body Colour.
    </button>
    <button id="change-text">
        Change Text
    </button>
    <button id="change-font">
        Change Font
    </button>
    <hr>
    <h1 id="head-1">Welcome to GfG</h1>
    <p>
        A Computer Science portal for geeks. It contains 
        well written, well thought and well explained 
        computer science and programming articles, quizzes 
        and practice/competitive programming/company interview 
        Questions.
    </p>
    <hr>
    <h1 id="head-2">Welcome to GfG</h1>
    <p>
        A Computer Science portal for geeks. It contains 
        well written, well thought and well explained 
          computer science and programming articles, 
        quizzes and practice/competitive programming
        /company interview Questions.
    </p>
    <script src="main.js"></script>
</body>
  
</html>


  • main.js

Javascript




<script>
  $("#body-color-changer").on("click", () => {
      $("body").css("background-color", "#101010");
      $("body").css("color", "white");
  });
  
  $("#change-text").on("click", () => {
      $('#head-1').text("World's Largest Pizza.");
      $('#head-2').text("Blue Coloured Elephant Discovered");
  })
  
  $("#change-font").click(() => {
      $('p').toggleClass('bigger');
  })
</script>


Output:

 

Using jQuery’s Built-In Methods to Add Effects: We saw how we can perform basic DOM manipulation using jQuery, using our own logic. jQuery also has some in-built methods that we can use to add effects on DOM elements.

Syntax:

$(CSS_selector).method_for_effect("optioanl_value")

Approach:

  • jQuery has three methods for the purpose of changing the visibility of elements, show(), hide(), and toggle(). 
  • show() method will show a hidden element. 
  • hide() method will hide a visible element.
  • toggle() method will show the element if it is hidden, and hide the element if it is visible.
  • We simply select an element of our choice and chain one of these methods on it.
  • Since we don’t want the show button to be visible when the paragraph is already visible, we hide this button, when the user clicks on this button. But the hide button must be visible, so we show it using the show() method.
  • Since we don’t want the hide button to be visible when the paragraph is already hidden, we hide it too when the user clicks on this button. But the show button must be visible, so we show it using the show() method.

Example 2: This is another example that illustrates the basic use of the jQuery library for calling the functions by downloading the jQuery Source file.

  • index.html

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta name="viewport" 
          content="width=device-width, 
                   initial-scale=1.0">
</head>
  
<body>
    <button id="hide-btn">Hide</button>
    <button id="show-btn" 
            style="display: none;">
            Show
    </button>
    <p class="hide-n-show">
        A Computer Science portal for geeks. It contains
        well written, well thought and well explained 
        computer science and programming articles, quizzes
         and practice/competitive programming/company 
         interview Questions.
    </p>
    <hr>
    <button id="toggle-btn">Toggle</button>
    <p class="toggle">
        A Computer Science portal for geeks. It contains 
        well written, well thought and well explained 
        computer science and programming articles, quizzes 
        and practice/competitive programming/company interview 
        Questions.
    </p>
    <script src="./jquery.js"></script>
    <script src="main.js"></script>
</body>
  
</html>


  • main.js

Javascript




<script>
  $("#hide-btn").click(() => {
      $('p.hide-n-show').hide();
      $("#hide-btn").hide();
      $("#show-btn").show();
  })
  
  $("#show-btn").click(() => {
      $('p.hide-n-show').show();
      $("#show-btn").hide();
      $("#hide-btn").show();
  })
  
  $("#toggle-btn").click(() => {
      $('p.toggle').toggle();
  })
</script>


Output:

 

Manipulate the Visibility of an Element using jQuery, while adding some effects to it: Similar to hide, show and toggle, jQuery has other inbuilt functions as well, such as fadeIn(), fadeOut(), fadeTo(), fadeToggle(), slideUp(), slideDown(), slideToggle(), etc. The procedure for calling these methods is exactly the same as shown above. Select a DOM element, and call any one of these methods on it. All this should be done based on an event. This event can be a click of a button, typing some text in an input field, hovering the mouse over an element, etc. It is also noteworthy that all these methods can be chained to one another to add multiple effects on an element. Example:

Approach:

  • Listen for the click event on the target button.
  • Inside the event listener, select the target DOM element, here, a paragraph.
  • Call the slideUp() method to hide it with a sliding-up effect.
  • Chain the slideDown() method to show the paragraph again with a sliding-down effect.
  • We can provide an optional argument to these methods, a value in milliseconds, to manipulate its duration.

Example 3: This is another example that illustrates the basic use of the jQuery library for calling the functions in order to manipulate the Visibility of an Element.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta name="viewport"
          content="width=device-width, 
                   initial-scale=1.0">
</head>
  
<body>
    <h1>
        Using jQuery's Built-In Methods to Add Effects.
    </h1>
    <h3>
        Task: Manipulate the Visibility of an Element using 
        jQuery, while adding some effects on it
    </h3>
    <h2>Demo of Chained Methods</h2>
    <button id="btn">Clicke Me</button>
    <p id="para">
        A Computer Science portal for geeks. It contains 
          well written, well thought and well explained
          computer science and programming articles, 
        quizzes and practice/competitive programming
        /company interview Questions.
    </p>
  
    <script>
         // if the button with id btn is clicked, 
          // the paragraph with id para is first 
       // hidden by sliding it upwards, then 
      // shown by sliding it downwards.
  
        $("#btn").click(() => {
            $("#para").slideUp(1000).slideDown(1000);
        })
    </script>
</body>
  
</html>


Output:

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads