How to embed jQuery into HTML page

jQuery is light weight JavaScript library which makes easier to use JavaScript on the web page.

You can perform your action in less code as compared to JavaScript.

This makes simpler to manipulate the HTML documents, traversing, event handling and performing AJAX request.

Compatible with most of the browsers and supports CSS3 selectors to find and style property manipulation.

How to embed jQuery into HTML page

 


Contents

  1. Download and Include
  2. Initialize
  3. External file
  4. Conclusion

 

1. Download and Include

  • Navigate to jQuery Official website.
  • The library is available in two versions – compressed and uncompressed. The compressed has less size as compared to uncompressed because it doesn’t have extra white spaces and comments. The uncompressed version is readable and easier to debug.
  • Download the compressed version.
  • Use <script > to include library in HTML either in <head> or <body>.
<script src='jquery-3.2.1.min.js'></script>
  • You can also use the available CDN to include the library.

Google CDN

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

Microsoft CDN

<script src='http://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.js'></script>

 

2. Initialize

In the web page write your jQuery code within document ready state in the <script > tag.

Example

In the example, I used CDN library and defined click event on the button. On the click change value of the textbox element.

<input type='text' id='txt1' />
<input type='button' id='button' value='Click me' />

<!-- Script -->
<script src='http://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.js'></script>
<script type="text/javascript">
$(document).ready(function(){
 
 $('#button').click(function(){
   $('#txt1').val("Button clicked");
 });
});
</script>

Output

Click on the button.


 

3. External file

  • Create a new script.js file and put the above script on it.
  • Include the script.js after the jQuery library.

script.js

$(document).ready(function(){
 
 $('#button').click(function(){
  $('#txt1').val("Button clicked");
 });
});

index.html

<input type='text' id='txt1' />
<input type='button' id='button' value='Click me' />

<!-- Script -->
<script src='http://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.js'></script>
<script src='script.js' type="text/javascript"></script>

Output

Click on the button.


 

4. Conclusion

You can either use the external jQuery library or CDN version to include the script.

If you have created an external script and using jQuery on it then it must be included after jQuery library script otherwise it wouldn’t work and generate the error.

Related Post

Spread the love

Be First to Comment

Leave a Reply

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