Removing an event handler
There are times when we will be done with an event handler we previously registered. Perhaps the state of the page has changed such that the action no longer makes sense. It is possible to handle this situation with conditional statements inside our event handlers, but it is more elegant to unbind the handler entirely.
Suppose that we want our collapsible style switcher to remain expanded whenever the page is not using the normal style. While the Narrow Column
or Large Print
button is selected, clicking on the background of the style switcher should do nothing. We can accomplish this by calling the .off()
method to remove the collapsing handler when one of the non-default style switcher buttons is clicked:
$(() => { $('#switcher') .click((e) => { if (!$(e.target).is('button')) { $(e.currentTarget) .children('button') .toggleClass('hidden'); } }); $('#switcher-narrow, #switcher-large') .click(() => {...