Is there any way in JavaScript or jQuery to detect when an event is finished propagating up the DOM? I have a jQuery click handler that gets attached (with target "html") on a click, and the very click that adds it is triggering it once it bubbles up to the target. I want to delay the handler attachment until propagation is done. I hear event.stopPropagation() is risky business, so I'd rather not use that.
Here's my code. #title-editable is an anchor tag. vclick is an event defined by jQuery Mobile. I get both console logs with one click on #title-editable.
$("#title-editable").on("vclick", function(event){
event.preventDefault();
console.log("First handler fired.");
/* Would like to detect completion of event propagation here
and only execute the next statement after that. */
$("html").one("vclick",function(){
console.log("Second handler fired.");
});
});
Edit: I think I have a workaround. Instead of .one for the inner event, I use .on so the event isn't detached the first time it fires. I check the target of the click event and only execute changes for the inner event, and detach the inner event, if the target isn't #title-editable.
$("#title-editable").on("vclick", function(event){
event.preventDefault();
console.log("First handler fired.");
$("html").on("vclick",function(event2){
console.log("Second handler fired.");
if(!$(event2.target).closest("#title-editable").length){
console.log("Execute changes here.");
$("html").off("vclick");
}
});