OneBite.Dev - Coding blog in a bite size

use jquery in javascript file

Code snippet for how to how to use jquery in javascript file with sample and detail explanation

Understanding how to utilize jQuery in a JavaScript file can greatly simplify your coding practices in the development process. This guide will walk you through incorporating jQuery into your JavaScript file, providing both the code snippets and the in-depth explanations to each advanced step.

Code Snippet

To start implementing jQuery in your JavaScript file, you first need to include the jQuery library. You can accomplish this by adding the following code to your HTML file.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

Afterwards, use jQuery code in your JavaScript file. Here’s an example:

$(document).ready(function() {
   $("p").click(function() {
      $(this).hide();
   });
});

Code Explanation

In the first part of the code, we include the jQuery library by using the <script> tag in our HTML file. The src attribute references the jQuery library which is hosted by Google. The 3.6.0 in the URL specifies the version number, which can be replaced according to your needs.

In our JavaScript file, we have written code that will hide all paragraphs when clicked.

The $(document).ready() method makes sure that the jQuery doesn’t get executed until the document is fully loaded. This is to prevent any jQuery code from running before the document is finished loading (is ready).

Inside $(document).ready(), we begin by targeting all <p> elements with $("p"). This uses the jQuery selector to grab every paragraph on the page.

Click is a jQuery event method used here, it is triggered when a user clicks on a paragraph. The syntax is $(selector).click(function).

The $(this) selector refers to the specific element that was clicked. Then, .hide() is a jQuery effect method that’s used to hide the specified elements—in this case, the paragraph that was clicked.

So in essence, when a user clicks on any paragraph (<p>), that particular paragraph is hidden from view. This is a basic illustration of how we can leverage the power of jQuery from within a JavaScript file.

javascript