There are some situations where you have to execute some events automatically like you have to raise button click event without any action on button.
There is jQuery trigger() method to execute any event automatically in javascript.
Syntax of jQuery trigger() method:
trigger(eventType); //where eventType is type of event like click event of button
Here I am explaining jQuery trigger() method to execute click event of HTML button.
<html>
<head>
<title> execute button click event automatically using jQuery trigger() method</title>
<script type="text/javascript" src="jquery.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 the above code, we have two HTML buttons btn1, btn2. We bind the click event for two buttons using bind() jQuery method.
var d = new Date();
if(d.getSeconds() % 2 == 0){
$('#btn1').trigger('click');
}
else{
$('#btn2').trigger('click');
}
Here we are raising the click events for two buttons alternatively. $('#btn1').trigger('click'); attaches the click event to the button btn1 and $('#btn2').trigger('click'); attaches the click event to the button btn2. So, jQuery trigger() method will raise click events for two buttons automatically.
If the datetime second value is even(i.e second%2 == 0) we are raising the btn1 click event and for odd we are raising the btn2 click event automatically.
Download source code: jQuerey_trigger.zip (35.79 kb)