Reputation: 3438
In my attempt to learn core JavaScript, I am now learning about EventListeners.
My problem is that in code below EventListener not being fired in IE (working just fine in Firefox and Chrome).
Can somebody please tell me what I am doing wrong?
My code is:
<p>The first captain of the USS Enterprise NCC-1701 was
<a id="wikipedia" href="http://en.wikipedia.org">Christopher Pike</a>.
</p>
<script type="application/javascript">
var link = document.getElementById("wikipedia");
// for firefox and other browsers
if (typeof link.addEventListener != "undefined")
{
link.addEventListener("click", clickListener, false);
}
// IE only
else if (typeof link.attachEvent != "undefined")
{
link.attachEvent("onclick", clickListener);
}
function clickListener()
{
var link = document.getElementById("wikipedia");
link.setAttribute("href", "www.example.com/");
open("http://www.example.com");
return false;
}
</script>
Upvotes: 0
Views: 2232
Reputation: 126105
Try to determine the browser using this method:
theFunction = function() { alert("Clicked!"); };
theElement = document.getElementById('wikipedia');
// All modern browsers
if (window.addEventListener) {
theElement.addEventListener('click', theFunction, false);
// IE
} else if (window.attachEvent) {
theElement.attachEvent('onclick', theFunction);
// Failure
} else {
alert("Your browser is definitely too old.");
}
Upvotes: 0
Reputation: 186562
Is that really the complete code? If so then the reference should be to 'clickListener' and not 'wikipediaLink.clickListener'.
The real issue is the attribute value "application/javascript" isnt IE friendly, change it to "text/javascript" and along with the function referencing and you should be good.
By the way, I would use an abstracted addEvent function - mine in particular fixes the 'this' keyword issue in JScript and also because of the initial assignment it doesn't need to check whether the element supports the addEventListener method or not since it checks the window object first:
var addEvent = (function() {
function addEventIE(el, ev, fn) {
return el.attachEvent('on' + ev, function(e) {
return fn.call(el, e);
});
}
function addEventW3C(el, ev, fn) {
return el.addEventListener(ev, fn, false);
}
return window.addEventListener ? addEventW3C:addEventIE;
})();
Usage:
addEvent( link, 'click', clickListener );
Upvotes: 3