How To Add jQuery link In Html Correctly With Examples

jQuery is a JavaScript framework that runs very fast with a very small size of JavaScript library code. It can easily implement a lot of JavaScript animation effects by operating DOM objects, processing events, and handling Ajax interactions. jQuery can simplify your JavaScript source code to improve your development speed and JavaScript code execution performance. In this article, I will tell you how to add jQuery links in both Html files and javascript files, and how to use jQuery to implement some basic animations with examples.

1. Add jQuery Link In Html File.

  1. The first thing you need to do is to download the jQuery library js file and add it into your Html file.
  2. Open a web browser and go to the jQuery library js file download page http://jquery.com/download/. Find the jQuery library js file download link, right-click it, in the popup menu list click Save Link As menu.
  3. The above action will save the jQuery library js file in a local folder, you can save it to any folder( for example your project lib folder).
  4. Next, you need to add the jQuery link in your Html page file like below source code. Below source code should be added in the head section of the target Html file.
    <script type="text/javascript" src="./lib/jquery-3.3.1.min.js"></script>
  5. The above source code will include jQuery lib js which is saved in your local machine, it is not an optimized way because the jQuery link will read the jQuery source file from your web server for each request, this will cost a lot of bandwidth usage and computer resource.
  6. A better way to add the jQuery link in the Html file is to include jQuery CDN online version. In this way, it can make the process of add jQuery more faster and stable. This can also reduce your website bandwidth usage.
  7. Below source code will add jQuery link from the Google provided jQuery CDN.
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  8. Now you had learned how to add  jQuery links in Html. Next, I will show you how to add the jQuery link in a javascript file.

2. Add jQuery Link In JavaScript File.

  1. If you add the jQuery link in the Html source code, you must add the below code in every Html file head section. The disadvantage of this method is that if you want to use a new jQuery version you must update all Html files one by one manually, this is not a good method.
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  2. To fix the above issue, you can add the jQuery link in a javascript file ( for example include-jquery.js ), and then include that js file in your Html pages. Thus if you want to use a new jQuery lib version, you just need to update the include-jquery.js file. Below are some examples.
  3. In this example, there is a <a> link in the Html page, when you click the link, it will pop up an alert dialog then the link text will fade out. The below video shows the effect.
  4. All below examples use test.html file, it only contains one <a> link.
    <a href="">click this link</a>

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/OvyqoKL97Y0

2.1 Use document.writeln() Function To Add jQuery Link In JavaScript File.

  1. Add below js code in the include-jquery.js file, and then import the include-jquery.js file in test.html.
  2. include-jquery.js
    // invoke javascript document object's writeln function to write 'import jquery lib js file string' in html page source code. 
    document.writeln('<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" type="text/javascript"></script>');
  3. use-jquery-when-jquery-is-loaded.js
    /* 
    Use $ to use jQuery object when the document load ready, then execute the anonymous funcion()
    */
    $(document).ready(function() {
    
      // Register click event to all html a tag, the callback function will be triggered when user click a link in the html page.   
      $('a').click(function(event) {
        
        // Prevent the link default behaviour, then click it will not open a target url.
        event.preventDefault();
        
        // Popup an alert dialog.
        alert('The link will fade out.')
        
        // Fade out the link in the html page.
        $(this).hide("slow");
      });
    });
  4. test.html
    <!-- include the js file which import jQuery, this code line must be wrote above all other js file that will use jQuery object -->
    <script src="./include-jquery.js"></script>
    
    <!-- below js file will use jQuery object when above js file execute complete -->
    <script src="./use-jquery-when-jquery-is-loaded.js"></script>
    
    <a href="">click this link</a>

2.2 Add jQuery By Create Script Element In Another JavaScript File.

  1. create-js-element-to-include-jquery-js-file.js
    // When the window load process complete then invoke load jquery lib js file function. 
    window.load = load_jquery_lib_js_file();
    
    function load_jquery_lib_js_file(){
    
        // Create a html script element.
        var script = document.createElement('script');
    
        // Set the html script element's type to 'text/javascript'.
        script.type = 'text/javascript';
    
        // Set the html script element's src attribute value to google online jquery lib js file.
        script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js';
        
        // When the jquery script load complete then invoke the handler function for different browsers.
        script.onreadystatechange = handler;
        script.onload = handler;
    
        // Append the html script element to the end of html page head section.
        document.getElementsByTagName('head')[0].appendChild(script);
    }
    
    
    // This function will be executed after jquery lib file has been loaded successfully.
    function handler(){
    
        // Write an message in browser console.
        console.log('jquery added :)');
    
        // Create a html script element.
        var script = document.createElement('script');
    
        // Set the html script element's type to 'text/javascript'.
        script.type = 'text/javascript';
    
        // Set the html script element's src attribute value to the js file which will use jQuery object( it is use-jquery-when-jquery-is-loaded.js in this example ).
        script.src = './use-jquery-when-jquery-is-loaded.js';
    
        // Append the html script element to the end of html page head section.
        document.getElementsByTagName('head')[0].appendChild(script);
    }
  2. use-jquery-when-jquery-is-loaded.js
    /* 
    Use $ to use jQuery object when the document load ready, then execute the anonymous funcion()
    */
    $(document).ready(function() {
    
      // Register click event to all html a tag, the callback function will be triggered when user click a link in the html page.   
      $('a').click(function(event) {
        
        // Prevent the link default behaviour, then click it will not open a target url.
        event.preventDefault();
        
        // Popup an alert dialog.
        alert('The link will fade out.')
        
        // Fade out the link in the html page.
        $(this).hide("slow");
      });
    });
  3. test.html
    <script src="./create-js-element-to-include-jquery-js-file.js"></script>
    
    <a href="">click this link</a>
  4. You can see the test.html file source code in chrome inspector ( How To Find Web Element Using Web Browser Inspector ) to find the appended script elements.

3. jQuery Example.

  1. This example contains two html files, hellow-world-alert.html and hello-world-add-number.html.

3.1 jQuery Hello World Alert Example.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/ZI-G8C3vmwk

  1. In the first example, it will display an alert dialog when the page is loaded.
  2. There is also a button with text “Welcome to JQuery world” in the page, when the button is clicked, it will show two alert dialog, the first alert dialog’s text is ‘You click the button’, the second alert dialog’s text is the button original text, then it will set button text to ‘Wish you like JQuery 🙂‘ and change the button’s text and background color.
  3. hello-world-alert.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8"/>
        <title>JQuery Hello World Example</title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script type="text/javascript">
    
            /*  When jQuery execute, it will first run the jQuery() function, you can implement it here.
            *
            *   Below code is similar to window.onload() = function(){......};, it will being executed when the page load process complete.
            *
            *   You can also use $(document).ready(function(){......}), $ is an alias of jQuery.
            *
            *   You can even use $(function(){......}) to process document load ready event.
            * */
            jQuery(document).ready(function(){
    
                // Display an alert dialog with message.
                alert('Hello World From JQuery.');
    
                // Return the button object with the button's id.
                var button = jQuery('#click_button')
    
                // This function will be executed when someone click the button.
                button.bind('click', function () {
    
                    // Retrieve original text of the button.
                    const original_text = jQuery(this).text();
    
                    // Show an alert dialog with text.
                    alert('You click the button');
                    
                    // Show the button's original text. 
                    alert('The original button text is : ' + original_text);
    
                    // Set new button text to 'Wish you like JQuery :)'. Set button text color to yellow, background color to blue.
                    jQuery(this).text('Wish you like JQuery :)').css({color:'yellow', background:'blue'});
                })
    
            });
        </script>
    </head>
    <body>
    <button id="click_button">
        Welcome to JQuery world.
    </button>
    </body>
    </html>

3.2 jQuery Hello World Add Number Example.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/u-x9_IQssaU

  1. This example uses jQuery to set the Html p tag css style. It also bind the mouse move event of the div tag, when your mouse moves in the div tag, the number will increase.
  2. hello-world-add-number.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>JQuery Add Number While Mouse Move</title>
        <!--<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>-->
        <script type="text/javascript" src="./lib/jquery-3.3.1.min.js"></script>
        <script type="text/javascript">
    
            // This is a global variable that defines the number font size.
            let number_size = 10;
            
            // $(function(){......}) equals to $(document).ready(function(){.....}) and jQuery(document).ready(function(){......})
            $(function(){
    
                // Set the html p tag style with css method. $ is an alias of jQuery.
                $('p').css({border: '15px solid green', color: 'red', padding: '10px'});
    
                // Set div css style, the div's id is add_number.
                $('#add_number').css({
                    margin: '5 auto',
                    backgroundColor: 'blue',
                    textAlign: 'left',
                    fontSize: '10px'
                })
    
                // Bind mousemove event to the selected add_number div object.
                // When user mouse move in add_number div then execute the function.
                $('#add_number').bind('mousemove', function(){
                    // Get current add_number div text and parse it to integer, default value is 5.
                    var current_number = parseInt($(this).text(), 10);
    
                    // Add 1 to the number font size.
                    number_size = number_size + 1;
    
                    // Increase 2 for current number.
                    current_number = current_number + 2;
    
                    // Set new value for current number in the div text.
                    $(this).text(current_number);
    
                    // Set the number font size with css.
                    $(this).css({color: 'yellow', fontSize: number_size+'px'})
                });
            });
        </script>
    </head>
    <body>
    
    <p>Hello World From JQuery!</p>
    
    <div id="add_number">0</div>
    
    </body>
    </html>

4. How Can I Add Existing jQuery Code To My Html Page.

4.1 Question.

  1. I get some jQuery code from the internet, and it meets my requirements, so I want to add those jQuery codes to my Html page. I tried some methods, but failed, can anyone give me some help? Thanks a lot.

4.2 Answer1.

  1. You can create a new javascript file such as common-function.js and then paste your jQuery code into it.
  2. You can save this file in your js project home-directory/js folder. Then you can follow this article to add both the jQuery library js file and the common-function.js file into your Html page ( refer to sections 1, 2 at the beginning of this article ).
  3. And then you can use the jQuery code that you get from the internet. But you also need to make sure the web element id or name in the jQuery code matches the web element in your Html web page.

5. How To Use jQuery To Include Html File Content.

5.1 Question.

  1. My Html page (index.html) contains several other Html pages using the <iframe> tag like below.
    <iframe src="menu.html"></iframe>
    
    <iframe src="detail.html"></iframe>
  2. And the content of the menu.html & detail.html is wrapped with a <div> tag, and there are some jQuery codes (used to response button click event) in them also.
  3. Now I have to add the jQuery library file in both the menu.html and detail.html to let it work as expected.
  4. But what I want is to include the jQuery library file in the index.html file only, and then run the jQuery code in the menu.html and detail.html successfully.
  5. Because I may include more Html files in the index.html file later, this way it can reduce the source code size and complexity.
  6. But when I include the jQuery code in the index.html file only, all the jQuery code in the included Html pages can not work as expected.
  7. How can I include an Html page using jQuery? Thanks a lot.

5.2 Answer1.

  1. You can use jQuery’s load() method to load the Html page content (menu.html, detail.html) into the DOM tree of the index.html page.
  2. Then the jQuery object that is created in the index.html page can access and manipulate the content of the menu.html, detail.html.
  3. Below is the example source code.
    <iframe id="menu"></iframe>
    
    <iframe id="detail"></iframe>
    
    <script>
    $(document).ready(function() {
    $('#menu').load('menu.html');
    
    $('#detail').load('detail.html');
    });
    </script>

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.