Question

I'm trying to figure out how to prevent the onBeforeUnload event from being triggered in IE9+ when using links without hrefs.

I've set up a fiddle here (a simplified test of a real scenario), which pretty much describes what I'm trying to accomplish. Whenever onBeforeUnload is triggered (ergo, when a link is clicked), the page background becomes blue. When using attachEvent I can easily return false to prevent that from happen. But when adding the link's click event with addEventListener, the return statement doesn't make any difference. More or less, I would like link 4 to behave like link 2.

Yes, changing from links to buttons would be a solution. Altering the onBeforeUnload functionality (like having that code as part och the click functionality) would be another. But sadly, I don't have control of those pieces of code.

So. Are there any way I can stop click events on links from trigger onBeforeUnload when set up with addEventListener? Or did MS remove this possibility when migrating from attachEvent to addEventListener, because it's generally a bad idea to prevent users from navigating away from a page?

Was it helpful?

Solution

When using addEventListener you can add a parameter to your listener function.
The parameter will contain the event which is fired (you can stop this)
Use event.preventDefault() assuming the parameter is called event.

See this jsFiddle as an example

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top