Published on: 15 December, 2015

Writing your first JQuery function.

Posted by andy | 689 views 1 likes 1 favourites 0 comments
Tumblr Digg Google Plus

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>
Comments

There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.
Related Articles
Published on: 22 March, 2016
In this tutorial, you will learn how to create a category menu list using css and JQuery framework. You will also learn on how to automatically place an arrow into the LI element if it founds there is a sub menu list. The placement of the arrow is done via JQuery, this includes binding the event onclick on the LI element as well to expand and collapse the sub menu list.