-1

I am trying to call an event handler with an argument. It works fine without an argument.

Where am I going wrong here?

var box = $("#box");

function changeColor (a) {
    $(this).css("background", a);
}

box.click(changeColor("green"));
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
navigator
  • 96
  • 1
  • 8

5 Answers5

2

You need to use call() to call your function inside click event:

var box = $("#box");

function changeColor (a) {
    $(this).css("background", a);
}

box.click(function(){
   changeColor.call(this, "green");
});

Fiddle Demo

Felix
  • 37,892
  • 8
  • 43
  • 55
0

Use .call()

Fiddle Demo

box.click(function(){
   changeColor.call(this, "green");
});
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
0

You are calling your changeColor function instead of passing it as callback. Instead you should do :

box.click(changeColor.bind(this, "green"));

The bind method creates a new function with arguments already filled, it is almost equivalent to doing :

box.click(function () {
    changeColor("green");   
});
joelrobichaud
  • 665
  • 4
  • 19
0
var box = $("#box");

function changeColor (a) {
    $(this).css("background", a);
}

box.click(function(){
   changeColor("green");
});
kakabali
  • 3,824
  • 2
  • 29
  • 58
0

You are trying to assign the return value of changeColor() to box.click() instead of the function itself. Wrapping changeColor() in a function as follows sets the box.click() to the function

box.click(function(){
   changeColor.call(this, "green")
});

See Fiddle

Josh Durham
  • 1,632
  • 1
  • 17
  • 28
  • this isn't working i tried this first – navigator Feb 20 '14 at 16:56
  • The problem was that you need to use `.call()` to set the context of the function call. So you end up setting the value of `this` within the callback. I modified my code to reflect this. – Josh Durham Feb 20 '14 at 17:12