Main Tutorials

How to trigger other elements event handler with jQuery

jQuery comes with a trigger() function to execute the event handlers that attached to elements. For instance,

A single click event bind to a button with an Id of “button1”.


$("#button1").bind("click", (function () {
		
	alert("Button 1 is clicked!");
			
}));

A single click event bind to a button with an Id of “button2”. and a trigger to execute the button1 click event handler.


$("#button2").bind("click", (function () {
		
	alert("Button 2 is clicked!");

	$("#button1").trigger("click");
			
}));

When button2 is clicked, the alert message “Button 2 is clicked!” is prompt, follow by button1 alert message “Button 1 is clicked!‘.

Try it yourself


<html>
<head>

<script type="text/javascript" src="jquery-1.4.2.min.js"></script>

</head>

<body>

<h1>jQuery trigger() example</h1>

<script type="text/javascript">

  $(document).ready(function(){
	
    $("#button1").bind("click", (function () {
		
	alert("Button 1 is clicked!");
			
    }));
	
    $("#button2").bind("click", (function () {
		
	alert("Button 2 is clicked!");

	$("#button1").trigger("click");
			
    }));
	
  });
</script>
</head><body>

<input type='button' value='Button 1' id='button1'>
<input type='button' value='Button 2' id='button2'>

</body>
</html>

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
kavoshkar
10 years ago

hi
i have a asp.net C# page that has javascript code that show me a popup dialog.it has input and submit button that i can input string on it. i have code behind function name SaveMe() to save data to sqlserver.
so i want when i click on submit button :
first: call SaveMe() Function on code Behind to save data to sql Servet
Second: hide this dialog.

please help me and send your response to my email
thanks.

Veronica
11 years ago

Thank you mjyong, could you show us an example of of how to trigger css style to ajax loaded content? I have elements that are loaded through ajax, and I would like my style to be applied. I have been able to apply the style if the user does something in the screen, but not when the content is loaded.

Thank you

??????
11 years ago

hi
thanks for your nice article. i have a question:
what is the difference between these code:

$("#button1").triggerHandler("click");
$("#button1").trigger("click");
$("#button1").click();