I found this code
<body>
<div id="div1">
What is 2+2?
</div>
<div id="div2">
<a href="answer.html" id="answer_link">Get the answer</a>
</div>
</body>
then the javascript
var d1 = document.getElementById("div1");
var a_link = document.getElementById("answer_link");
a_link.onclick = function()
{
d1.innerHTML = "That is easy, the answer is <strong>4</strong>!";
return false;
};
so this code works because it changes the inner html in the div1
and doesn’t load the page that the link makes reference but what if i want to use event listeners?
i write this
a_link.addEventListener( 'click', function(){
d1.innerHTML = "That is easy, the answer is <strong>4</strong>!";
return false;
}, false);
but it doesn’t prevent the link to load the reference how can i use an event listener that works the same way that the little piece of code of above?
Use
e.preventDefault()for normal browsers andevent.returnValuein older IE browsers:Actually, older versions of IE don’t even support
addEventListener(), so the IE part of the code is only needed if you’re using the same callback function withattachEvent()as you are withaddEventListener()which I do.