I am trying to delay the default event or events in a jQuery script. The context is that I want to display a message to users when they perform certain actions (click primarily) for a few seconds before the default action fires.
Pseudo-code: - User clicks link/button/element - User gets a popup message stating 'You are leaving site' - Message remains on screen for X milliseconds - Default action (can be other than href link too) fires
So far, my attempts look like this:
$(document).ready(function() {
var orgE = $("a").click();
$("a").click(function(event) {
var orgEvent = event;
event.preventDefault();
// Do stuff
doStuff(this);
setTimeout(function() {
// Hide message
hideMessage();
$(this).trigger(orgEvent);
}, 1000);
});
});
Of course, this doesn't work as expected, but may show what I'm trying to do.
I am unable to use plugins as ths is a hosted environment with no online access.
Any ideas?
Something like this should do the trick. Add a new class (presumably with a more sensible name than the one I've chosen) to all the links you want to be affected. Remove that class when you've shown your popup, so when you call .click() again your code will no longer run, and the default behavior will occur.
This might work:
Note: totally untested
I would probably do something like this.
I'm not sure if
url
can be seen from inside the timed function. If not, you may need to declare it outside the click handler.Edit: If you need to trigger the event from the timed function, you could use something similar to what karim79 suggested, although I'd make a few changes.
Edit: After some testing and research, I'm not sure that it's actually possible to trigger the original click event of an
<a>
element. It appears to be possible for any element other than<a>
.Probably the best way to do this is to use unbind. Something like: