Setting up jQuery

Author: MDBootstrap


To use jquery you need to add it's dependency to your project.

You can test your jQ code in our snippets without setting up your environement localy.


External References

Note: If you are using MDB package you don't have to modify anything! Download MDB package to skip this lesson.

External scripts can be referenced with a full URL or with a path relative to the current web page.

This example uses a full URL to link to a jQuery script. This is the best way of implementing external scripts if you don't build your project with mdb package which is highly recommended.


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

This example uses a downloaded jQuery script located in a specified folder on the current web site:


      <script src="/js/jquery-3.4.1.js"></script>
    

This example links to a script located in the same folder as the current page:


      <script src="jquery-3.4.1.js"></script>
    

The <script> Tag

In HTML, jQuery code has to be inserted (just like JavaScript code) between <script> and </script> tags.


      <script>
        $('#example').html("My First jQuery script");
      </script>
    

You can place any number of jQuery scripts in an HTML document.

jQuery scripts can be placed just like regular JavaScript's - in the <body>, or in the <head> section of an HTML page, or in both.


Good practices

In most cases, the best place to place JavaScript code is the bottom of the <body> element.

Placing scripts at the bottom of the <body> element improves the display speed, because script compilation doesn't slows down the display.


External JavaScript files

jQuery scripts can also be placed in external files like regular JS scripts.

jQuery files have the file extension .js.

To use an external script using jQuery, put the name of the script file in the src (source) attribute of a <script> tag after you added jQuery references:


      <script src="jquery-3.4.1.js"></script>
      <script src="myJQScript.js"></script>
    

Note: And again - it's a good practice to place external JavaScript files at the bottom of the <body> element.

Here is a full example of a ready starting index.html file:


      !DOCTYPE html>
      <html lang="en">

      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title>Start file</title>
      </head>

      <body>
        <p id="example"></p>
        <!-- JQuery -->
        <script src="https://code.jquery.com/jquery-3.4.1.js"></script>
        <!-- Your code -->
        <script>
          // Just an example
          $('#example').html("My First jQuery script");
        </script>
      </body>

      </html>
    

Let's use jQuery in next lesson!


Previous lesson Next lesson

Spread the word:
Do you need help? Use our support forum

About the author