Prevent the click event just created from firing
Here is a simplified example of the problem I am facing. Let's say I have this HTML code:
<div id="test">Hello</div>
I have the following event handler attached to this div
:
$("#test").on("click", function() {
console.log("Clicked test!");
$(document).one("click", function() {
console.log("Clicked on document!");
});
});
Here's the jsFiddle of this example.
If I click on "Hello", ideally I would only like "Clicked test!" appear in my console and for "Click on document!" appears after I click a second time. However, both log messages appear when the click event bubbles up to the object document
and fires this new click event. Is there a way to prevent this from happening without using stopPropagation
, which could have other unexpected side effects?
source to share
My solution is kind of hackish, but it actually works. If you set up your document click handler asynchronously, the event won't bubble:
$("#test").on("click", function(e) {
console.log("Clicked test!");
setTimeout(function(){
$(document).one("click", function() {
console.log("Clicked on document!");
});
}, 10);
return true;
});
See the modified fiddle: https://jsfiddle.net/voveson/qm5fw3ok/2/
source to share
Or use and turn off with selectors:
$(document).on("click", "#test", add_doc_click)
function add_doc_click() {
console.log("Clicked test!");
$(document).on("click", function (e) {
console.log("Clicked on document!");
})
$(document).off("click", "#test", add_doc_click)
}
https://jsfiddle.net/y2q1gocu/
EDIT: Test and click every time:
$(document).on("click", "#test", add_doc_click)
function add_doc_click() {
console.log("Clicked test!");
$(document).on("click", function (e) {
console.log("Clicked on document!");
})
$(document).on("click", "#test", function (e) {
console.log("Clicked test!");
})
$(document).off("click", "#test", add_doc_click)
}
source to share
You can use a class that determines if an element was clicked or not.
$("#test").on("click", function(e) {
console.log("Clicked test!");
if($(this).hasClass('clicked')){
$(document).one("click", function(e) {
console.log("Clicked on document!");
});
}else{
$(this).addClass('clicked');
}
});
source to share