To use jQuery in a web project, you have two primary options: download jQuery from the official website or include it via a Content Delivery Network (CDN).
Downloading jQuery:
You can download the jQuery library from the official website jquery.com. Choose the version you want and download the minified or uncompressed version of jQuery. Once downloaded, include it in your project by placing the jQuery file in your project directory.
Using a CDN:
Alternatively, you can include jQuery in your project directly from a CDN. CDNs host popular libraries and frameworks, allowing you to include them in your project without downloading them. Here's an example of including jQuery from the Google CDN:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Incorporating jQuery into HTML Documents:
Once you've set up jQuery in your web project, you can start incorporating it into HTML documents to enhance interactivity and functionality.
Basic Syntax:
jQuery uses a simple syntax to select elements and perform actions on them. The basic syntax is:
$
: The jQuery symbol, also known as the alias for thejQuery
function.selector
: A string that specifies the elements to be selected.action()
: A jQuery method that performs an action on the selected elements.
Example:
Let's create a simple HTML document and incorporate jQuery to change the text of a paragraph when a button is clicked.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<p id="demo">Click the button to change this text.</p>
<button id="btn">Click Me</button>
<script>
$(document).ready(function(){
$("#btn").click(function(){
$("#demo").text("Hello, jQuery!");
});
});
</script>
</body>
</html>
In this example:
- We include jQuery from the Google CDN in the
<head>
section. - We have a paragraph element with the id
demo
and a button element with the idbtn
. - We use jQuery to select the button element and attach a click event handler to it.
- When the button is clicked, the text of the paragraph with id
demo
is changed to "Hello, jQuery!" using the.text()
method.
Practice Excercise Practice now