jquerycallbackselectorjquery-callback

Send jQuery Selector to Callback Function


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);

Solution

  • 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>