Source for the HTML page - index.html
<html> <head> <title>jQuery Beginners Tutorial</title> <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js" type="text/javascript"></script> <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js" type="text/javascript"></script> <script type="text/javascript" src="app.js"></script> </head> <body> <p> This is a beginners Tutorial to get you started with jQuery. We are going to add some Text inside the DIV tag mySection using jQuery and also learn how to capture events such as click. </p> <div id="mySection"> </div> </body> </html>
Source for the JavaScript file using jQuery - app.js
$(document).ready(function() { $("#mySection").html("<b>This text was added using jQuery</b>"); $("p").click(function(event){ alert("Thanks for visiting mysamplecode.com!"); }); });
Comparisons to plain JavaScript
- jQuery uses $(document).ready(function()) which similar to the window.onload = function(){}. It basically runs all the jQuery scripts after the page loading is complete to avoid DOM errors.
- $("#mySection").html(someValue) is basically doing the same thing as document.getElementById('mySection').innerHTML = someValue
- $("p").click(function(event){} add a click listener to the element and then passes the event to the function where you can take some action. Its similar to listening for an onClick event in Javascript. we are just doing an alert here to demonstrate the click event.
In this example we have used the jQuery library (jquery.js) from google. You can also download the jQuery library from the jQuery website and put that in your server, but there are advantages to using the google library over your own one. The library usaully gets loaded faster as google has better server than ours, also there is chance that the user visited another site that has used the same library so it may be already be cahched by the browser resulting in faster page load time. The jQuery library is also hosted on other CDN networks such as Microsoft, jQuery, etc.
No comments:
Post a Comment
NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.