jQuery's .click - pass parameters to user function

JavascriptJqueryFunctionParameter Passing

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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);
}

Solution 2 - Javascript

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
}

Solution 3 - Javascript

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().

Solution 4 - Javascript

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 );

Solution 5 - Javascript

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});

Solution 6 - Javascript

      $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');

Solution 7 - Javascript

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.

Solution 8 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPaul HofferView Question on Stackoverflow
Solution 1 - JavascriptChris KempenView Answer on Stackoverflow
Solution 2 - JavascriptNick CraverView Answer on Stackoverflow
Solution 3 - Javascriptuser113716View Answer on Stackoverflow
Solution 4 - JavascriptGravity GraveView Answer on Stackoverflow
Solution 5 - JavascriptKevinView Answer on Stackoverflow
Solution 6 - JavascriptVladimir NovickView Answer on Stackoverflow
Solution 7 - Javascriptsusan097View Answer on Stackoverflow
Solution 8 - JavascriptshaedrichView Answer on Stackoverflow