311

I am trying to call a function with parameters using jQuery's .click, but I can't get it to work.

This is how I want it to work:

$('.leadtoscore').click(add_event('shot'));

which calls

function add_event(event) {
    blah blah blah }

It works if I don't use parameters, like this:

$('.leadtoscore').click(add_event);
function add_event() {
    blah blah blah }

But I need to be able to pass a parameter through to my add_event function.

How can I do this specific thing?

I know I can use .click(function() { blah }, but I call the add_event function from multiple places and want to do it this way.

shaedrich
  • 5,457
  • 3
  • 26
  • 42
Paul Hoffer
  • 12,606
  • 6
  • 28
  • 37
  • this is adopted from `patricks` answer, which I think is a great solution: http://www.jsfiddle.net/naRRk/1/ – jAndy Jul 17 '10 at 21:56

8 Answers8

554

For thoroughness, I came across another solution which was part of the functionality introduced in version 1.4.3 of the jQuery click event handler.

It allows you to pass a data map to the event object that automatically gets fed back to the event handler function by jQuery as the first parameter. The data map would be handed to the .click() function as the first parameter, followed by the event handler function.

Here's some code to illustrate what I mean:

// say your selector and click handler looks something like this...
$("some selector").click({param1: "Hello", param2: "World"}, cool_function);

// in your function, just grab the event object and go crazy...
function cool_function(event){
    alert(event.data.param1);
    alert(event.data.param2);
}
Muhammad Dyas Yaskur
  • 6,914
  • 10
  • 48
  • 73
Chris Kempen
  • 9,491
  • 5
  • 40
  • 52
  • For me, I had to remove the data part, e.g. alert(event.param1); I'm using jquery 1.10.2, maybe they've changed something? – Family May 15 '13 at 15:34
  • @Family - May I ask where you found jQuery v1.10.x? I can't seem to find a download for it / any related documentation... – Chris Kempen May 15 '13 at 20:50
  • Whoops, sorry, I was looking at my jquery-ui.min.js file by mistake, sorry, I should have written jquery 1.9.1. – Family May 15 '13 at 21:26
  • @Family - Haha no problem! I've just tested your suggestion using jQuery 1.9.1, but I can't get it working at all. I need the `.data.` parameter included. Is it possible that you are declaring your parameter variables such that they are available within the scope of your 'click' function? – Chris Kempen May 15 '13 at 21:33
  • 1
    I am dynamically creating the object on the server side and binding the click event with: r.OnClientClick = "imageClicked({param1: '" + obj.Command + "' });return false"; Then on the client side I have: function imageClicked(event) { if (event.param1 == "GOTO PREVIOUS") {... If I use event.data.param1 it says that it's undefined. Now I've typed it out here, I can see the difference, d'oh! – Family May 16 '13 at 01:43
  • 1
    @Family - Haaha no problem, it's nice to help, even through comments ;) – Chris Kempen May 16 '13 at 09:50
  • The only problem with this solution that you can't use your function in other parts of the code where you just want to call it with the normal parameters and not with an event. – totymedli Aug 21 '13 at 09:59
  • 5
    @totymedli - I guess you could always call it somewhere else, passing an object of the same structure: `var param_obj = {data : {param1: "Hello", param2: "World"}}; cool_function(param_obj);` ? – Chris Kempen Aug 22 '13 at 07:45
  • 1
    This is so much better than using HTML5 data- attributes, thank you! (And solves JSHint complaining about using 'this' in the callback too!) – Matthew Herbst Oct 28 '14 at 23:22
  • Doesn't seem to work when the parameter is some jquery variable. – cregox Feb 15 '15 at 01:51
  • this is fine for static parameters, how about dynamic ones? – MC9000 Aug 27 '19 at 18:43
  • @MC9000 - It's difficult to comment without a more detailed example, but I imagine variables could be used instead of string values, or alternatively your function itself could fetch / calculate the values you need, thereby avoiding the need to pass values altogether :) – Chris Kempen Aug 28 '19 at 08:27
  • Did it this way to call a function "toggleplay". I keep forgetting about "this" $('[id^=VOctrl]').click(function () { toggleplay(this.id, this.name); }); – MC9000 Aug 28 '19 at 20:41
87

You need to use an anonymous function like this:

$('.leadtoscore').click(function() {
  add_event('shot')
});

You can call it like you have in the example, just a function name without parameters, like this:

$('.leadtoscore').click(add_event);

But the add_event method won't get 'shot' as it's parameter, but rather whatever click passes to it's callback, which is the event object itself...so it's not applicable in this case, but works for many others. If you need to pass parameters, use an anonymous function...or, there's one other option, use .bind() and pass data, like this:

$('.leadtoscore').bind('click', { param: 'shot' }, add_event);

And access it in add_event, like this:

function add_event(event) {
  //event.data.param == "shot", use as needed
}
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • When you say just, does that mean only? Secondly, does that mean I would be able to use $(this) inside my add_event function like I normally would inside the anonymous function? – Paul Hoffer Jul 17 '10 at 21:36
  • 2
    @phoffer - Yes, "just" means no params, *only* the function name, it's a reference to the function, not the result of running the function you want to assign to the `click` handler. In the anonymous method and `.bind()` examples above you can use `this`, it'll refer to the `.loadtoscore` you clicked on (like you'd expect). In the last example, inside `add_event(event)` the same is true, use `this` or `$(this)` and it'll be what you want. – Nick Craver Jul 17 '10 at 21:41
  • 1
    @phoffer: You would have to pass the element explicitly in order to use it, e.g.: `function(){ add_event('shot', $(this));}` and `function add_event(event, element){...}`. `element` would be a jQuery element here (it works with `bind()` though as Nick mentioned). – Felix Kling Jul 17 '10 at 21:41
  • @Felix - He can also use `$(this)` inside the function, for example: http://jsfiddle.net/tSu5t/ – Nick Craver Jul 17 '10 at 21:44
37

I had success using .on() like so:

$('.leadtoscore').on('click', {event_type: 'shot'}, add_event);

Then inside the add_event function you get access to 'shot' like this:

event.data.event_type

See the .on() documentation for more info, where they provide the following example:

function myHandler( event ) {
  alert( event.data.foo );
}
$( "p" ).on( "click", { foo: "bar" }, myHandler );
Gravity Grave
  • 2,802
  • 1
  • 27
  • 39
37

If you call it the way you had it...

$('.leadtoscore').click(add_event('shot'));

...you would need to have add_event() return a function, like...

function add_event(param) {
    return function() {
                // your code that does something with param
                alert( param );
           };
}

The function is returned and used as the argument for .click().

user113716
  • 318,772
  • 63
  • 451
  • 440
11

Yes, this is an old post. Regardless, someone may find it useful. Here is another way to send parameters to event handlers.

//click handler
function add_event(event, paramA, paramB)
{
    //do something with your parameters
    alert(paramA ? 'paramA:' + paramA : '' + paramB ? '  paramB:' + paramB : '');
}

//bind handler to click event
$('.leadtoscore').click(add_event);
...
//once you've processed some data and know your parameters, trigger a click event.
//In this case, we will send 'myfirst' and 'mysecond' as parameters
$('.leadtoscore').trigger('click', {'myfirst', 'mysecond'});

//or use variables
var a = 'first',
    b = 'second';

$('.leadtoscore').trigger('click', {a, b});
$('.leadtoscore').trigger('click', {a});
Kevin
  • 2,752
  • 1
  • 24
  • 46
6
      $imgReload.data('self', $self);
            $imgReload.click(function (e) {
                var $p = $(this).data('self');
                $p._reloadTable();
            });

Set javaScript object to onclick element:

 $imgReload.data('self', $self);

get Object from "this" element:

 var $p = $(this).data('self');
  • Awesome! Sadly, this is the only thing that works when I try to use jquery variables! no idea why. :| – cregox Feb 15 '15 at 01:51
6

I get the simple solution:

 <button id="btn1" onclick="sendData(20)">ClickMe</button>

<script>
   var id; // global variable
   function sendData(valueId){
     id = valueId;
   }
   $("#btn1").click(function(){
        alert(id);
     });
</script>

My mean is that pass the value onclick event to the javascript function sendData(), initialize to the variable and take it by the jquery event handler method.

This is possible since at first sendData(valueid) gets called and initialize the value. Then after jquery event get's executed and use that value.

This is the straight forward solution and For Detail solution go Here.

susan097
  • 3,500
  • 1
  • 23
  • 30
2

Since nobody pointed it out (surprisingly). Your problem is, that $('.leadtoscore').click(add_event); is not the same as $('.leadtoscore').click(add_event('shot'));. The first one passes a function, the second a function invocation so the result of that function is passed to .click() instead. That's not what you want. Here's what you want in vanilla JavaScript terms:

$('.leadtoscore').click(add_event.bind(this, 'shot'));

Function.prototype.bind() passes the function to .click() just like in the first example but with bound this and arguments that will be accessible on invocation.

shaedrich
  • 5,457
  • 3
  • 26
  • 42