Reputation: 35
I have a two-part development problem. In the first part, I set up several delegated event handlers:
$('#content').on('click','#button1',function1);
$('#content').on('click','#button2',function2);
Inside function1 and function2, among other processing, I set global variables to indicate which button was clicked:
function1(e) {
...
var whichButtonClicked = $('#button1');
...
}
function2(e) {
...
var whichButtonClicked = $('#button2');
...
}
Later, other code needs to remove the handler.
$('#content').off('click',whichButtonClicked,theFunctionRun);
However, the .off handler isn't working. It DOES work if I hardcode it to one of the buttons like this:
$('#content').off('click','#button1',theFunctionRun);
but then I lose the capability of being able to run it after either button functions.
How do I correct this statement:
$('#content').off('click',whichButtonClicked,theFunctionRun);
to make my code work?
I CAN run other commands on it, such as:
whichButtonClicked.trigger('click');
JSFiddle: https://jsfiddle.net/nLorh2wm/20/
Upvotes: 1
Views: 240
Reputation: 3637
Try just removing the $(...)
around the element:
Note: The snippet doesn't seem to show alerts, but you can see it working here: https://jsfiddle.net/rplittle/nLorh2wm/23/
$(document).ready(function() {
$('#content').on('click', '#button1', function1);
$('#content').on('click', '#button2', function2);
$('#content').on('click', '#buttonAfter', followUpFunction);
});
var theButtonClicked;
var theFunctionRun;
function function1(e) {
alert('in function1');
theButtonClicked = '#button1';
theFunctionRun = function1;
}
function function2(e) {
alert('in function2');
theButtonClicked = '#button2';
theFunctionRun = function2;
}
function followUpFunction(e) {
$('#content').off('click', theButtonClicked, theFunctionRun);
}
<div id="content">
<button id="button1">
Button 1
</button>
<button id="button2">
Button 2
</button>
<button id="buttonAfter">
Turn Off Handler for Button 1
</button>
</div>
Upvotes: 1