Pass arguments to a callback function in jquery click event

10,624

Solution 1

The clean way to handle this is to return a function:

function printNumber(number) {
   return function(e) {
       console.log(number);
   };
}

And then use:

$(".number").click(printNumber(number));

Solution 2

You can pass data to the callback directly as event.data in jQuery

$(".number").on('click', {number : 4}, printNumber);

function printNumber(event){
   console.log(event.data.number); // 4
}

Another way would be to use bind

$(".number").click(printNumber.bind($, 4));

function printNumber(number, event){
   console.log(number); // 4
}

But that would also change the callbacks this value

Share:
10,624
sheriff_paul
Author by

sheriff_paul

Frontend/mobile developer

Updated on June 19, 2022

Comments

  • sheriff_paul
    sheriff_paul almost 2 years

    Straight to the business:

    I have a jquery event listener that looks like this:

    $(".number").click(printNumber);
    

    and a callback function:

    function printNumber(number){
       console.log(number);
    }
    

    I was wondering if I could pass an argument to a callback so it will look something like this

    $(".number").click(printNumber(number));
    

    (I know that it immediately invokes that function, but still, is there a way to pass arguments to it)

    Thank you in advance!

  • Robert Moskal
    Robert Moskal over 8 years
    Returning the function is the cleaner way.
  • adeneo
    adeneo over 8 years
    @RobertMoskal - passing event.data is the jQuery'ish way, it's why it's there
  • Dmitry  Yaremenko
    Dmitry Yaremenko over 8 years
    In printNumber code is not obvious that you have event.data.number, but it may be useful when $number.off('click', printNumber)
  • Shady Mohamed Sherif
    Shady Mohamed Sherif about 7 years
    really thanx, bind worked for me