The best way to start your first JQuery function is after the browser has completedly loaded the page content. There are two short methods to do so. Please review the following function.
$(function(){ //Enter your code here }); $(document).ready(function(){ //Enter your code here });
Let's have an example that you want to attach an event to a button when the page has loaded. The button will popup an alert message saying that you are clicking this button. We can write the example of the function like below. We will target based on the ID and the class of the button.
<input type ='button' value='Click Me' id='btnTest' class='testClassButton'/> $(function(){ //first alternative by targeting the button via ID $("#btnTest").click(function(){ alert('You are clicking this button.'); }); $(".testClassButton").click(function(){ alert('You are clicking this button.'); }); });
Based on the above code, you can see that we can either target the ID or class of the button object. So which one is better? You will target the class if you want an event to be attached to a collection of the same objects. In this case, you can target multiple buttons that have the same class name. So, if you only have one event that you want to attach to a button, you can use the ID instead.
See the following full html source of above example.
<!DOCTYPE html> <html> <head> <title>Your first jquery function.</title> </head> <body> <p>Please click the following button to see your first JQuery event click function.</p> <input type ='button' value='Click Me' id='btnTest' class='testClassButton'/> <script type='text/javascript'> $(function(){ //first alternative by targeting the button via ID $("#btnTest").click(function(){ alert('You are clicking this button.'); }); $(".testClassButton").click(function(){ alert('You are clicking this button.'); }); }); </script> </body> </html>