jQuery Get Started

Getting started with jQuery is simple. Follow these steps to include jQuery in your project and begin using its powerful features to simplify JavaScript development.

1. Including jQuery in Your Project

There are two primary ways to include jQuery in your web project:

a. Using a CDN (Content Delivery Network)

This is the easiest and most common way to include jQuery. By linking to a jQuery file hosted on a CDN, you can load it directly into your project.

Add the following <script> tag in the <head> or before the closing <body> tag of your HTML file:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

Try It Now

b. Downloading and Hosting jQuery Locally

Alternatively, you can download jQuery from the official website and include it in your project.

  1. Download the jquery.min.js file.
  2. Save it in your project directory.
  3. Link it in your HTML file:
    <script src="path/to/jquery-3.6.0.min.js"></script>
    

    Try It Now

2. Basic jQuery Structure

Once jQuery is included, you can start writing jQuery code. A common pattern is to ensure that your code runs only after the document is fully loaded. Use the $(document).ready() function for this purpose:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery Get Started</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            // Your jQuery code goes here
        });
    </script>
</head>
<body>
    <p>Hello, jQuery!</p>
</body>
</html>

Try It Now

3. Writing Your First jQuery Code

Here’s a simple example that changes the text of a paragraph when a button is clicked:

<!DOCTYPE html>
<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://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("button").click(function(){
                $("p").text("jQuery is now working!");
            });
        });
    </script>
</head>
<body>
    <p>Click the button to change this text.</p>
    <button>Click Me</button>
</body>
</html>

Try It Now

  • Explanation:
    • The $(document).ready() function ensures that the jQuery code runs only after the DOM is fully loaded.
    • $ is used to access jQuery, and $("button").click() sets up an event listener on the button.
    • The $("p").text() method changes the text content of the paragraph.

4. Common Issues and Troubleshooting

  • Ensure jQuery is Loaded: Check the console for errors if jQuery is not working. Make sure the <script> tag is correctly linked.
  • Code Placement: Place your <script> tags either in the <head> section or just before the closing <body> tag. Avoid placing jQuery code before including the jQuery library.