jQuery is an extremely popular and widely used JavaScript library that simplifies HTML document traversal, manipulation, event handling, and animation. In this article, we will discuss how to run jQuery code inside your JavaScript.
Step 1: Include the jQuery library
Before you can use jQuery in your JavaScript code, you need to include the jQuery library in your HTML file. You can either download the library and host it on your server or include it directly from a Content Delivery Network (CDN) like Google or Microsoft. Here’s how to include it using the Google CDN:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
Step 2: Write your jQuery code
Once you’ve included the jQuery library in your HTML file, you can use its powerful features in your JavaScript code. Remember that jQuery is just a library built on top of JavaScript, so you can use it along with your regular JavaScript code.
Example: Hide an element with the “hide-button” class when clicked
In this example, we will use jQuery to hide an HTML element when it’s clicked. First, add the HTML element with the class hide-button:
<button class="hide-button">Click me to hide!</button>
Now, add the following jQuery code in your JavaScript:
$(document).ready(function() { $('.hide-button').click(function() { $(this).hide(); }); });
This code uses the $(document).ready() function to make sure the entire document is loaded before executing the jQuery code. Inside the function, we use the $(‘.hide-button’) selector to target all elements with the “hide-button” class. We then attach a click event handler using the .click() method, which hides the clicked element using the $(this).hide() method when the event is triggered.
Step 3: Run your jQuery code inside a script tag or a separate .js file
You can either place your jQuery code inside a <script> tag in your HTML file or create a separate JavaScript (.js) file and include it in your HTML file.
Option 1: Inside a script tag
Place your jQuery code inside a <script> tag after the jQuery library inclusion:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(document).ready(function() { $('.hide-button').click(function() { $(this).hide(); }); }); </script>
Option 2: In a separate .js file
Create a new JavaScript file (e.g., main.js) and add your jQuery code to it:
// main.js $(document).ready(function() { $('.hide-button').click(function() { $(this).hide(); }); });
Then, include this file in your HTML after the jQuery library:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script src="main.js"></script>
And that’s it! You can now use the powerful jQuery features within your JavaScript code to create interactive and dynamic web applications. Happy coding!