How To Append 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 operate 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 append jQuery link in both html file and javascript file, and how to use jQuery to implement some basic animations with examples.

1. Append jQuery Link In Html File.

The first thing you need to do is to download jQuery library js file and append it into your html file.

  1. Open a web browser and go to 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.
    download-jQuery-library-js-file-webp
  2. Above action will save the jQuery library js file in a local folder, you can save it to any folder( for example the project lib folder like below picture).
    save-jquery-js-file-in-local-project-lib-folder-webp
  3. Next you need to append 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>
  4. 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.
  5. A better way to append jQuery link in html file is to include jQuery CDN online version. In this way it can make the process of append jQuery more faster and stable. This can also reduce your website bandwidth usage. Below source code will append jQuery link from jQuery CDN google.
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  6. Now you had learned how to append jQuery link in html. Next I will show you how to append jQuery link in javascript file.

2. Append jQuery Link In JavaScript File.

If you append jQuery link in html source code, you must add 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>

To fix above issue, you can append 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.

In this example, there is a <a> link in the html page, when you click the link, it will popup an alert dialog then the link text will fade out. Below video shows the effect.

All below examples use test.html file, it only contains one <a> link.

<a href="">click this link</a>

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

Add below js code in the include-jquery.js file, and then import the include-jquery.js file in test.html.
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>');

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");
  });
});

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 Append jQuery By Create Script Element In Another JavaScript File.

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);
}

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");
  });
});

test.html

<script src="./create-js-element-to-include-jquery-js-file.js"></script>

<a href="">click this link</a>

You can see the test.html file source code in chrome to find the appended script elements.

include jquery js file in js code dynamically

3. jQuery Example.

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

save-jquery-js-file-in-local-project-lib-folder-webp

3.1 jQuery Hello World Alert Example.

In the first example, it will display an alert dialog when the page is loaded. 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.

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.

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.

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>
0 0 vote
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
0
Would love your thoughts, please comment.x
()
x