First, let us incorporate the javascript file (the library) into our existing webpage.
<head> <title>Page Title</title> <meta name... /> <meta name... /> <script src="https://code.jquery.com/jquery-1.9.1.min.js"></script> <script src="js/other-script-if-any.js"></script> ...Note that the library must be included in the <head> section of your webpage, preferrably at the top of all other included scripts. This will ensure that other included scripts are able to use jQuery library included at top. Here I have shown how to use the library from a remotely hosted location (called CDN). You can also download the latest version of jQuery and upload it to your own server to include it in your webpages. Now we’ll use jQuery in our page. You can write your code in <script> tag and place it in the <body> or <head> tag of your webpage, or else you can write it in a js file and include it in the <head> section of the page. Ideally definition of functions should go to the <head> part. And the function call should be within the <body>. Following example will alert a popup message on page load.
$(document).ready(function(){ alert("Hello World"); };Now we will retrieve the value of a text field in the webpage.
var valueOfField = $('#inputEmail').val();
<input type="text" name="emailId" id="inputEmail" value="somerandommail@akj243kh4jdjf.com" />There are several kinds of selectors available in jQuery. Selectors are syntax used to select desired nodes in the DOM. In the above example I’ve used ID Selector (#), which is equivalend to document.getElementById() method of standard javascript. To learn in details about jQuery selector, visit this page. Following example shows how to manipulate the html content inside a div tag on the web page.
$('#myDivId').html('<a id="myLink" href="http://www.google.com/">Google</a>'); //change the value with setter method alert($('#myDivId').html()); //the getter methodOne of the several popular usages of jQuery is it’s easy to use AJAX APIs. In the following example I’ll show how to make a simple server side call with jQuery to retrieve data and add to DOM.
$.ajax({ method: 'get', //method in which xml http request is sent url: 'date.php', //the url to sent the request to data: 'service=gettime', //the data to be sent in the request, can be your form input field's data callback: function(respons){ //the function called, when the response for the request is received $('#myDivId').html('Current time is ' + respons); } });There are many other usages of jQuery like animation, interactive UI design, custom input field creation (like a slider input) etc. I’ll keep writing more tutorials on jQuery. In the meanwhile you can have a look at jQuery API Documentation. Start using jQuery today, before it’s too late. Because, you can never attract your visitors as much as you can do, if your webpages are designed with jQuery.