How to use jQuery library and call functions from it ?
Last Updated :
29 Jul, 2024
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.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport"
content="width=device-width,
initial-scale=1.0">
<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>
<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>
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.
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>
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:
Similar Reads
How to use resize() function in jQuery ?
In this article, we will learn about the resize() method which is an inbuilt method provided by jQuery. This method is used for binding an event listener to the resize event. This event is fired when the size of the browser window changes its size, either by the user or due to some other reason. Thi
2 min read
How to use jQuery Each Function in TypeScript ?
jQuery is a JavaScript library that can be integrated with TypeScript and the features of both can be used together to enhance the interactivity of the application. In this post, we will learn, how we can use each() method of jQuery in TypeScript with its practical implementation. Before going to th
2 min read
How to Use jQueryâs ajax() Function for Asynchronous HTTP Requests ?
In this article, we are going to see how we can use jQuery's ajax() function to call backend function asynchronously or in other words HTTP Requests. AJAX is a set of web development techniques used by client-side frameworks and libraries to make asynchronous HTTP calls to the server. AJAX stands fo
4 min read
How to Call a JavaScript Function from an onsubmit Event ?
The onsubmit event attribute in HTML is triggered when a form is submitted. It is also useful for validating form data or performing actions before any submission and ensures better control and validation of user inputs before data is sent. The below methods can be used to call a JavaScript function
2 min read
How to define jQuery function ?
Defining the function in jQuery is different from JavaScript, the syntax is totally different. A function is a set of statements that takes input, do some specific computation and produce output. Basically, a function is a set of statements that performs some specific task or does some computation a
2 min read
How to call a function when content of a div changes using jQuery ?
The task is to call a function when the content of a div is changed. You can achieve this task by using the in-built method known as .change(). In simple words whenever the field is been changed we call a function that will throw a pop-up. .change(): This method will only trigger when some change oc
2 min read
How to use a jQuery library in your project ?
In this article, we will see how to use the jQuery library in a project. There are two methods to add a jQuery library to a project which are Include jQuery library from CDN linkDownload the jQuery library from the official website Include jQuery library from CDN link: CDN stands for Content Deliv
2 min read
How to use .on and .hover in jQuery ?
jQuery .on() method: This method is used to attach an event listener to an element. This method is equivalent to the addEventListener in vanilla JavaScript. Syntax: $(element).on(event, childSelector, data, function) Parameter event: It specifies the event to attach (click, submit, etc.). childSelec
2 min read
How to use autocomplete search in jQuery ?
In this article, we are going to see how to use search auto-complete in JQuery. For this, we are going to use the jQuery inbuilt function called autocomplete. We will do that in two different stages. Create a basic HTML file and add an input bar to it. Implement the autocomplete functionality. HTML
2 min read
Call a Parent Window Function from an iframe
Accessing a parent window's code or functions from a child window is possible. By using an iframe, a window can be opened to communicate with the parent. This guide provides simple syntax and code for calling functions in the parent window from the child window.Syntax:<a onclick="parent.abc();" h
1 min read