jQuery .on() method - passing argument to event handler function

Paramore picture Paramore · Apr 9, 2013 · Viewed 61.8k times · Source

I have the following script which does not work

<script type="text/javascript" >

   function ADS(e){ alert(e); }

   $(document).ready(function(){
          $(document).on("dblclick","#an_tnam tr", ADS('hello'));
          $(document).on("dblclick","#kv_tnam tr", ADS('world'));
          // ....  
 });

</script>

how can I pass argument to event handler function ADS ?

Answer

David Barker picture David Barker · Apr 9, 2013

You can pass extra data to an event handling function and can be accessed using event.data within the handler.

$(document).on('dblclick', '#an_tnam tr', { extra : 'random string' }, function(event)
{
    var data = event.data;

    // Prints 'random string' to the console
    console.log(data.extra);
}

You can also send extra data to any event you like when triggering the event from an external source using the .trigger() method

$('#an_tnam tr').trigger('click', [{ extra : 'random string' }]);

The difference with passing data to the trigger method is that it expects the handler to take extra arguments of the length of the array passed in. The above would expect the handler to have one extra argument to contain the object passed in.

$('#an_tnam tr').on('click', function(event, obj)
{
   // Prints 'random string' to the console
   console.log(obj.extra);
}