Anu145
Anu145

Reputation: 125

addEventListener doesnt fire on click in IE

I have the below code and the "alert" doesn't happen on click on the said element. But addEventListener seems to be supported by the IE I use (version 10) as I checked with another simple program and it worked fine.

var iframe1 = document.getElementsByName('frStatus')[0];
var innerDoc = (iframe1.contentDocument) ? iframe1.contentDocument : iframe1.contentWindow.document;
innerDoc.getElementById('slow_jquery').innerHTML = slowjquerycount;
innerDoc.getElementById('slow_jquery').style.color="red";
console.log("doc"+document.getElementById("slow_jquery"));
innerDoc.getElementById('slow_jquery').addEventListener("click", function(){
       alert("event listener");
});

The corresponding html is

<span id="slow_jquery" style="cursor:pointer;color:green;">0</span>

When the above code is executed & the element is clicked, no error is thrown, no warning on console, and the alert message is not shown. Is there anything wrong with the code ? Any help is going to be of much use.

Thanks in advance.

Note: - Already tried using z-index to ensure the element is not hidden behind another. - Code works fine in Chrome. - Ensured that IE-10 supports addEventListener.

Upvotes: 1

Views: 434

Answers (2)

Bram Vanroy
Bram Vanroy

Reputation: 28554

You are trying to bind a listener to a dynamically added element. That's easy in jQuery with .on(). In plain JS it's a bit more difficult: you'll have to use event delegation.

Make sure the argument to querySelector is an element that exists on load, and isn't added dynamically! In this case I assume that iframe1 is such an element.

document.querySelector(iframe1).addEventListener("click", function(event) {
  if (event.target.id === "slow_jquery") {
    alert("event listener");
  }
});

Also see this answer:

CAVEATS! The example Fiddle only includes code for the standards-compliant browsers (i.e., IE9+, and pretty much every version of everyone else) If you need to support "old IE's" attachEvent, then you'll want to also provide your own custom wrapper around the proper native functions. (There are lots of good discussions out there about this; I like the solution Nicholas Zakas provides in his book Professional JavaScript for Web Developers.)

Upvotes: 1

Pavel Gatnar
Pavel Gatnar

Reputation: 4053

Try element.onclick=function instead of registering 'click' event listener.

Upvotes: 2

Related Questions