Sunday, March 6, 2011

Trigger javascript events manually

Hi,

This is a very interesting code segment I got from one of my friends. In this you can actually trigger any event manually. This gets very useful in daily programming, when you want to perform same set of task/s with multiple events. I am not referring to creating a common function, but creating a single function or set of functions and the event which is calling the function, you can actually cause the event to occur via code.

First of all you need to download a stable version of jquery.js and use it in your following code:


<html>
<head>
<title> execute button click event automatically using jQuery trigger() method</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {          
$('#btn1').bind('click', function() {
alert('You selected the First Button');
});
$('#btn2').bind('click', function() {
alert('You selected the Second Button');
});


var d = new Date();
if(d.getSeconds() % 2 == 0){
$('#btn1').trigger('click');
}              
else{
$('#btn2').trigger('click');
}
});  
</script>
</head>
<body>
<input type="button" id="btn1" value="First Button" />
<input type="button" id="btn2" value="Second Button" />    
</body>
</html>

In this code the main highlight is the $('#btn1').trigger('click') and $('#btn2').trigger('click') sections. It triggers the click event for id's btn1 and btn2. There is also another section in this code,


$('#btn1').bind('click', function() {
.....
}

Here we are just bindling and event to an object. In this case we are binding the "click" event for the object id "btn1"

Best of luck! :)

No comments:

Post a Comment