I have the following JavaScript/jQuery code that starts the listener that highlights the DOM elements.
I click a button and I start the listener event. ex: highlight : function()
When I click something in the webpage, I stop the listener.
Now, when I click the button again, I want to restart the listener event.
highlight : function()
{
if(isHighlighting){
isHighlighting = false;
$(document).unbind("mousemove", highlighter);
return false;
}
$(document).bind("mousemove", highlighter);
isHighlighting = true;
},
I also have the code that catches the onclick event, and stops the DOM element highlighter
function highlighter(e) {
var cur, overlay = $("#overlayhighlightclosetaffair"),
no = [document.body, document.documentElement, document];
if (e.target === cur) {
return;
}
if (~no.indexOf(e.target)) {
cur = null;
overlay.hide();
return;
}
var target = $(e.target),
offset = target.offset(),
width = target.outerWidth(),
height = target.outerHeight();
cur = e.target;
overlay.css({
top: offset.top,
left: offset.left,
width: width,
height: height
}).show();
$(document).click(
function() {
if(isHighlighting){
isHighlighting = false;
$(document).unbind("mousemove", highlighter);
console.log('click');
}
});
}
You don’t need to unbind the event, and can simplify your logic.
This is not a fully functional example, but it should be a good starting point. I suggest structuring the code so that
isHighlightingis not global.Here is an alternative solution using binding and unbinding. I do not recommend this approach, but this is a much better way the handle unbinding and rebinding. Forgetting to set
isHighlight = false. Is a much less serious bug than forgetting to unbind the event. It would result in a memory leak and multiple calls to an event handler is more likely to have worse side effects.