49

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 ?

Paramore
  • 1,313
  • 2
  • 19
  • 37
  • Your best bet would definitely be, in this case, to run it as an anonymous function, like a few have describe here. $('.el').on('click', function () { callback('argument') }); – Ricardo Magalhães Nov 27 '14 at 15:34

6 Answers6

126

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 .on() expects the handler to take extra arguments of the length of the array passed in. The above would expect the handler to have (only) 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);
}
Viktor Borítás
  • 135
  • 2
  • 11
David Barker
  • 14,484
  • 3
  • 48
  • 77
  • 23
    As far as I can see, this is the only answer that actually answers the question asked. – Jacob Hume Jul 15 '13 at 14:11
  • 1
    `console.log(data.extra);` <-- Don't you mean, in the 1st example? And in the second `console.log(obj.extra);` might be helpful. – Bob Stein Jan 24 '16 at 20:23
  • @BobStein-VisiBone I've added that in to help clarify. – David Barker Mar 16 '16 at 09:42
  • 1
    This is the only solution that allows you to properly remove -using jQuery `off()` - just that particular handler if and when you like. If you pass to the `on()` an anonymous function (or the result of a function invocation) that gets hold of its extra data with a closure, then you can no longer `off()` that specific handler alone. – Marcus Junius Brutus May 16 '17 at 14:52
  • 1
    I concur, this should be the correct answer. I needed this for a hover function that was calling a function twice once on mouseenter and again on mouseleave, but I needed some way of passing the arguments to the named function. This answer did the trick. – Studocwho Jan 15 '19 at 00:11
54

The .on() function expects a function reference to be passed; what you're doing is calling the function and passing its return value. If you need to pass a parameter you'll need to wrap the call in an anonymous function.

$(document).on('dblclick', '#an_tnam tr', function(event) {
    ADS('hello');
});

jQuery always passes its normalized event object as the first argument to the function to be executed.

Anthony Grist
  • 38,173
  • 8
  • 62
  • 76
  • 5
    Of course, if the function `ADS()` actually returned a function object, everything would be fine. – Blazemonger Apr 09 '13 at 14:13
  • Sorry but had to downvote because this answer does not answer the real question, just solves another issue. – Vinicius Tavares Dec 11 '14 at 06:17
  • @ViniciusTavares No need to apologise for downvoting, though I'd prefer it if you actually explained *why* you think that. – Anthony Grist Dec 11 '14 at 10:26
  • 2
    Actually, there is a neater syntax for that, using JS bind(): `$(document).on('dblclick', '#an_tnam tr', ADS.bind(null, 'hello'));` First parameter is the value you want "this" to have inside callback function. – Ignacio Segura Feb 19 '16 at 16:24
  • 2
    well i upvoted @AnthonyGrist because i'm tired of all the downvoting for stupid crap... like why so picky...whatevs... i countered his downvote :) – carinlynchin Jul 21 '16 at 12:55
6

As Anthony Grist pointed out, the .on() method is expecting a function reference at that part; you're evaluating a function which returns nothing (null).

However, one fun feature of JavaScript is that everything is an object, including functions. With a small modification, you can change ADS() to return an anonymous function object instead:

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

http://jsfiddle.net/cSbWb/

Blazemonger
  • 90,923
  • 26
  • 142
  • 180
6

Actually, there is a very neat simple way to achieve this, with no extra clutter and no anonymous functions, using JS bind():

$(document).on('dblclick', ADS.bind(null, 'hello'));

First parameter is the value you want "this" to have inside callback function.

MOre info in Mozilla Developer Network: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind

Ignacio Segura
  • 678
  • 8
  • 15
4
function ADS(e){ alert(e); }

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

 });

will do the trick.

akluth
  • 8,393
  • 5
  • 38
  • 42
3
function ADS(e) {
    return function() {
        alert(e);
    };
}

Like that when you're doing

$(document).on("dblclick","#an_tnam tr", ADS('hello'));

, it is the returned function that is assigned as event handler (and your string argument is passed when you're assigning the handler, not when it's called).