stackOverNo stackOverNo - 1 month ago 6
HTML Question

How do you pass an instance of the control being clicked when adding the on click from jquery?

I am working on a side navigation bar and have a label around the actual links in the sidebar to provide padding and borders. I would like the user to be able to click anywhere in this label and go to the link. I wrote this function for that:

function allowLabelClick(control) {
$(control).find('a')[0].click();
}


If you add this inline to the onclick of an individual label and pass (this) as the paramter, it works fine. However I basically have 100 or so links all with the class 'outerLabel' and don't want to add an onclick to each one manually. Instead I'd like to add it to all elements with the class outerLabel. To do that I wrote this line:

$('.outerLabel').on("click", allowLabelClick());


in my javascript. However I don't know what to pass in the parameter for allowLabelClick. I want it to be the DOM element that was clicked on but "this" doesn't work and I'm not sure what else to try.

Thanks

Answer

Use an anonymous function:

$('.outerLabel').on("click", function() { allowLabelClick(this); });