Send jQuery Selector to Callback Function

243 Views Asked by At

How can I send the jQuery selector to a callback function? For example, the following code, on a button click, would hide the button selected by the jQuery object.

function cb (target) {
    target.hide();
}

$('#button').on('click', cb);
1

There are 1 best solutions below

4
Rory McCrossan On BEST ANSWER

The function is executed within the scope of the element that raised the event so you don't need to pass anything - just use the this keyword. Eg. $(this).hide():

function cb() {
  $(this).hide();
}

$('#button').on('click', cb);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">Hide me!</button>