Search code examples
jquerytriggersclick

JavaScript/jQuery – how to differentiate between a triggered and user click?


this question looks similar like In Jquery, how can I tell between a programatic and user click?

But i am not able to get it, my code

<div class="sample_class" onclick="sample_fn(arg1,arg2,arg3,arg4, e);" ></div>
<div class="trigger_class" onclick="trigger_fn()></div>


function sample_fn(arg1,arg2,arg3,arg4, e){
    console.log(e) ;
    console.log(e.isTrigger);
    console.log(e.hasOwnProperty('originalEvent'));
}


function trigger_fn(){
    $(".sample_class").trigger("click")
}

on click on div.sample_class i am getting in console Object undefined false

on clicking div.tigger_class i am getting in console same thing Object undefined false

I am unable to differentiate between these two clicks. Thanks in advance


Solution

  • UPDATE: As of jQuery 1.7+, the event object (e in the code below) object will contain a property named e.isTrigger which is true if the event was triggered and undefined if not triggered; this is undocumented so check this (demo) before using it. If using an older version of jQuery, use the code below.


    It might just be easier to pass a flag to your function. Here is a demo:

    HTML

    <button>Trigger a click below</button>
    
    <div id="test">Click Me</div>​
    

    Script

    ​$('#test').click(function(e, triggered){
        var msg = (triggered) ? ', triggered' : '';
        console.log('clicked' + msg);
    });​​
    
    $('button').click(function(){
        // pass a true flag to the click function to indicate
        // it's been triggered
        $('#test').trigger('click', true);
    });
    

    Update: data-attributes can contain valid JSON which is automatically ​converted into an object (demo):

    <div class="test" data-args='{ "quantity": 1, "type": "pizza", "extra1": "peperoni", "extra2": "cheese", "extra3": "cheesy bread" }'>Click Me</div>
    

    Note that the data-arg uses a single quote to contain the JSON, but the JSON inside MUST use double quotes around each key and value (unless it's numeric).

    Then use the data method to extract the information:

    var args = $(this).data('args');
    

    Alternatively, you can make a separate data-attribute for each argument (demo):

    <div class="test" data-quantity="1" data-type="pizza" data-extra1="peperoni" data-extra2="cheese" data-extra3="cheesy bread">Click Me</div>
    

    Then use gather all of the data from the element as follows:

    var args = $(this).data();