55

I am trying to set the onclick event using javascript. The following code works:

var link = document.createElement('a');
link.setAttribute('href', "#");
link.setAttribute('onclick', "alert('click')");

I then use appendChild to add link to the rest of the document.

But I obviously would like a more complicated callback than alert, so I tried this:

link.onclick = function() {alert('clicked');};

and this:

link.onclick = (function() {alert('clicked');});

But that does nothing. When I click the link, nothing happens. I have testing using chrome and browsing the DOM object shows me for that element that the onclick attribute is NULL.

Why am I not able to pass a function into onclick?

EDIT:

I tried using addEventListener as suggested below with the same results. The DOM for the link shows onclick as null.

My problem may be that the DOM for this element might not have been fully built yet. At this point the page has been loaded and the user clicks a button. The button executes javascript that builds up a new div that it appends to the page by calling document.body.appendChild. This link is a member of the new div. If this is my problem, how do I work around it?

8
  • 3
    Try addEventListener('click', function() {...}) Commented Nov 30, 2012 at 0:18
  • 1
    I actually end up writing an article about this. Commented Nov 30, 2012 at 0:19
  • 1
    link.onclick = function () { ... }; should work: jsfiddle.net/sZHkt/1 Commented Nov 30, 2012 at 0:22
  • Works for me , not sure what is the problem here. Commented Nov 30, 2012 at 0:24
  • In your article, you mention to be careful to make sure the DOM is ready to be manipulated. Perhaps my problem is I am trying to set onclick too soon? I am building up an entire div and appending it to the page after the page has loaded. So the page loads, the user clicks a button that runs javascript that creates a div with my link inside it. Do I need to do something to make sure the link is built before I can set the onclick? Commented Nov 30, 2012 at 0:35

7 Answers 7

50

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 :-(

Sign up to request clarification or add additional context in comments.

4 Comments

I have no idea why it wasn't working before, but the jquery code seems to have magically fixed whatever was wrong.
jsfiddle doesnt allow alert because someone can easily make a fiddle like while(true) alert("gotcha sucka"), and I dont think I need to explain why that's an issue
@Werlious I may be confused, but why it would be problem? JSfiddle runs sandboxed code on client, right?
Yes, so let's say I share a fiddle with you. You won't know until you open it, but the JS in the fiddle is while(true) alert("harhar"). You open the fiddle to see what it is, and when jsfiddle loads the fiddle, it also generates the preview, which runs the js, and now your computer is spamming alerts at you, generally slowing down your browser/computer faster than you can react. Now you have been DOSed. Replace that with say an infected image on say a stagefright era android and now you have some real problems
15

If you're doing this with JavaScript, then use addEventListener(), with addEventListener('click', function(e) {...}) to get the event stored as e. If you don't pass in the event like this, it will not be accessible (although Chrome appears to be smart enough to figure this out, not all browsers are Chrome).

Full Working JSBin Demo.

StackOverflow Demo...

document.getElementById('my-link').addEventListener('click', function(e) {
  console.log('Click happened for: ' + e.target.id);
});
<a href="#" id="my-link">Link</a>

Comments

8

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');
   });
}

Comments

2

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.

Comments

2

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>

Comments

2

If you have a named function, i.e., function funcName() {...} already defined, then the process is simply to identify onclick with the name of the function:

document.getElementById("myBtn").onclick = displayDate;

function displayDate() {
    document.getElementById("demo").innerHTML=Date();
}
<button id="myBtn">Try it</button>
<p id="demo"></p>

This can help keep your code better organized. A function can be quite long, and defining it singularly to a single onclick, and not some independent variable that can be referenced later, might end up creating spaghetti code.

Comments

0

This is the best way!

<a id="btn" onclick='alert("Hello people up vote please...! Thanks");'>Run Function</a>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.