Haresh Vidja Haresh Vidja - 3 months ago 10
jQuery Question

How to detect trigger method call event in jQuery

I want to detect triggered click event in javascript, my code is

$(".my_button").click(function(){

// if event fired form .trigger() method from other method or event then do something

// actuall code for click event is here
})

.....
.....

$('.other_first_button').click(function(){
// code of other first button
$(".my_button").trigger('click');
});

.....
.....

$('.other_second_button').click(function(){
// code of other second button
$(".my_button").trigger('click');
});


Note: I want to identify click event call using jquery
trigger()
method in
$(".my_button").click()
.

Thanks in advance for your time.

Answer

Pass a parameter to the trigger click event as

$(".my_button").trigger('click', ['btn2']);

Recieve it in click event on my button as

$(".my_button").click(function(e, p2){

Not check if p2 is undefined or has some value, if it has it has been triggered using a trigger() event

$(".my_button").click(function(e, p1){

    // if event fired form .trigger() method from other method or event then do something
    if(p1 != undefined)
	alert('triggered from ' + p1);
    // actuall code for click event is here
})


$('.other_first_button').click(function(){
    // code of other first button
    $(".my_button").trigger('click', ['btn1']);
});


$('.other_second_button').click(function(){
    // code of other second button
    $(".my_button").trigger('click', ['btn2']);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button class="other_first_button">
First
</button>
<button class="other_second_button">
Second
</button>
<button class="my_button">
mybtn
</button>

JSFIDDLE

Comments