Link to home
Start Free TrialLog in
Avatar of MJ
MJFlag for United States of America

asked on

How to modify addEventListener code to work for IE8

I have the following code that works to get the ID of an element when clicked but I also need this to work in IE8 which doesn't support addEventListener so how can I get this to work in IE8 also (***without browser sniffing - please use feature detection instead)?
document.addEventListener('click', function(e) {
    e = e || window.event;
    var target = e.target || e.srcElement;
    if(target.id != "")
    {
        alert(target.id);
    }
     
}, false);

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Robert Schutt
Robert Schutt
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of MJ

ASKER

What I want is code that listens for a click on an element and then reads the "ID" as the initial code does but also works with IE8 which the current code doesn't do. Ive looked at some of the articles on this but I don't know Javascript enough to to do this without a lot of trial and error.

Thanks!
I have tested the updated fiddle with IE8 through the url http://jsfiddle.net/robert_schutt/4pd4xuvs/2/embedded/result/ and it works the same as the previous fiddle on other browsers as far as I can tell. Can you be more specific about what and/or how it's not working for you, have you tried to make a page with this code and debug with F12 for example? Are you able to share a link to a page where it's not working for you?

I know this is not convincing per se but here is a screenshot showing my IE version and the alert working.
User generated image
Avatar of MJ

ASKER

Hi Robert,
Let me test and I will get back to you.

Thanks,
MJ
Avatar of MJ

ASKER

Thanks Robert!