I am trying to set the onclick event using javascript. The following code works:
var link = document.createElement(\'a\');
link.setAttribute(\'href\', \"#\");
l
Setting an attribute doesn't look right. The simplest way is just this:
link.onclick = function() {
alert('click');
};
But using addEventListener as JCOC611 suggested is more flexible, as it allows you to bind multiple event handlers to the same element. Keep in mind you might need a fallback to attachEvent for compatibility with older Internet Explorer versions.
Use sth like this if you like:
<button id="myBtn">Try it</button>
<p id="demo"></p>
<script>
document.getElementById("myBtn").onclick=function(){displayDate()};
function displayDate()
{
document.getElementById("demo").innerHTML=Date();
}
</script>
I have been unable to reproduce the problem. Contrary to the OP's findings, the line below works fine on the latest versions of IE, FF, Opera, Chrome and Safari.
link.onclick = function() {alert('clicked');};
You can visit this jsFiddle to test on your own browser:
http://jsfiddle.net/6MjgB/7/
Assuning we have this in the html page:
<div id="x"></div>
The following code works fine on the browsers I have tried it with:
var link = document.createElement('a');
link.appendChild(document.createTextNode("Hi"));
link.setAttribute('href', "#");
link.onclick= function() {link.appendChild(document.createTextNode("Clicked"));}
document.getElementById("x").appendChild(link);
If there is a browser compatibility issue, using jQuery should solve it and make code much much more concise:
var $link = $("<a>").html("Hi").attr("href","#").click(function (){$link.html("Clicked")})
$("#x").html($link)
If brevity is not a strong enough argument for using jQuery, browser compatibility should be ... and vise versa :-)
NOTE: I am not using alert() in the code because jsFiddle does not seem to like it :-(
You can add a DOM even listener with addEventListener(...)
, as David said. I've included attachEvent
for compatibility with IE.
var link = document.createElement('a');
link.setAttribute('href', "#");
if(link.addEventListener){
link.addEventListener('click', function(){
alert('clicked');
});
}else if(link.attachEvent){
link.attachEvent('onclick', function(){
alert('clicked');
});
}