0

I need to execute code from 3 different places on my website when an event gets triggered. I've added 3x listeners but for some reason only the first listener gets called.

Here's the code I'm testing at the moment: JSFiddle

window.addEventListener('tompina_event', function (e) {
    document.write("triggered 1");
});

window.addEventListener('tompina_event', function (e) {
    document.write("triggered 2");
});

window.addEventListener('tompina_event', function (e) {
    document.write("triggered 3");
});



var evt = new CustomEvent('tompina_event');
window.dispatchEvent(evt);

Result:

triggered 1

This is the result I was hoping for:

triggered 1triggered 2triggered 3
2
  • Any of those listeners will wipe the whole document out when it's fired for the first time. There wil be no elements to listen ... Commented Jan 4, 2017 at 12:52
  • use console.log() instead of document.wirte()cause you're overwriting the whole page. Commented Jan 4, 2017 at 12:54

2 Answers 2

2

It works, but the document.write destroys the original page and thus the execution of other code.

Please rewrite so the result is set in an other way like alert("triggered 1") or console.log("triggered 1").

Sign up to request clarification or add additional context in comments.

1 Comment

Wow, I was sure I was missing something obvious, but this is even embarrassing, thanks a ton! Works as intended!
1

The problem is with document.write(). Each call is overriding the strings from the previous call, and it appears that only one is firing. Change to console.log(), or document.body.innerHTML += "" and you will see them all firing.

The write() method is mostly used for testing: If it is used after an HTML document is fully loaded, it will delete all existing HTML.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.