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. Question & Answer.

4.1 How Can I Add Existing jQuery Code In My Html Page.

  1. I get some jQuery code from internet, and it meets my requirements, so I want to add those jQuery code in to my Html page. I tried some time, but failed, can anyone give me some help? Thanks a lot.
  2. You can create a new javascript file such as common-function.js and then paste your jQuery code into it. 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 seciton 1, 2 at the beginning of this article ). 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 match the web element in your Html web page.
0 0 votes
Article Rating
Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments
Clicky
0
Would love your thoughts, please comment.x
()
x