jQuery Get Started
To use jQuery you only need to add one script file to your page. There are two common ways.
1. Use a CDN (the easy way)
A CDN (Content Delivery Network) is a fast server which hosts the file for you. Put this line before your own script, usually at the end of the body:
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
The official CDN is code.jquery.com. Many other CDNs like Google and cdnjs host it too. Check the jQuery website for the current version and the integrity hash for the secure option.
2. Download the file
Download the file from the jQuery website (jquery.com) and keep it in your project folder. Then link it with a normal relative path:
<script src="js/jquery-3.7.1.min.js"></script>
The file with .min in the name is the compressed (minified) one for the live site. The other one is easier to read, for learning and debugging.
3. Install with npm (for build tools)
npm install jquery
Your first jQuery page
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My first jQuery page</title>
</head>
<body>
<h1 id="title">Hello</h1>
<button id="btn">Change title</button>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function () {
$('#btn').click(function () {
$('#title').text('Hello jQuery');
});
});
</script>
</body>
</html>
When you click the button, the heading text changes to “Hello jQuery”. Let us run the same code to see the result:
<h1 id="title">Hello</h1>
<button id="btn">Change title</button>
$(document).ready(function () {
$('#btn').click(function () {
$('#title').text('Hello jQuery');
});
$('#btn').click(); // we simulate the click here, a user would click with the mouse
});
<h1 id="title">Hello jQuery</h1>
<button id="btn">Change title</button>
Check that jQuery is loaded
If the version number shows, jQuery is working:
<p>Page</p>
console.log($.fn.jquery);
console.log(typeof jQuery);
3.7.1
function
The output above is from jQuery 3.7.1. The same check works in the browser console of your page.
Common problems
- “$ is not defined”: the jQuery file is not loaded, or your code runs before it. Load jQuery first.
- A wrong file path or a typo in the file name gives a 404 error. Check the Network tab of the browser.
- Loading jQuery two times can break plugins.
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |