This will not work:
$('#myElement').click(ElementClicked($(this)));
Executes the ElementClicked() function with what this at the time of writing, and binds the return value of ElementClicked() to the click event. Which is nothing in this case.
You need to pass the function to the click event, for example:
$('#myElement').click(function () { ElementClicked($(this)); });
This makes a (n anonymous) function that will be bound to the click event, and the function calls ElementClicked() at startup, passing this . The ElementClicked function can be defined as:
function ElementClicked(elem) { elem.addClass('clicked'); }
As you noticed, this inside the function bound to the event will be a click of the element. Therefore, instead of creating a functional shell that calls the function that passes the element, you can simply shorten it as follows:
$('#myElement').click(ElementClicked); function ElementClicked() { $(this).addClass('clicked'); }
Note that the function is passed to click() as a variable instead of being executed immediately, since there are no brackets () after it.
And BTW, you probably mean addClass instead of addCss .
deceze
source share