IMG-LOGO

Writing your first JQuery function.

andy - 15 Dec, 2015 3521 Views 0 Comment

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 Blogs

Related Tutorials

DOM Element Selection in JQuery

Learn how easily to manipulate DOM element selection using JQuery One of the cool feature from JQuery is the DOM selector In javascript when you want to reference an object you can refer the object either based on ID or ...

Event Handling in JQuery

So what actually an event? An event can be considered as a result of an action triggered by a process which can be a process clicking of a user or when a page is loading.

What is JQuery?

Learn what is the JQuery framework is and why many web developers and designers love to this framework.