Ethan McTague
Ethan McTague

Reputation: 2358

JS element onclick event not being fired

I have an <a> element, which I have selected using the dom. I have the following code:

var link = document.createElement("a");
var ce = function (e) {
   alert("A");
}
link.onclick = ce; // Or link.addEventListener("click", ce);
console.log(ce);
console.log(link.onlick);

In the console (chrome dev tools), I see the following:

function (e) { alert("A"); }

and then

undefined

Upon clicking the element, the event does not fire. I have noticed that applying the onclick to the same element from the console, however, does correctly apply the event.

How to I get this event to apply?

Upvotes: 0

Views: 123

Answers (2)

cнŝdk
cнŝdk

Reputation: 32145

In fact, The problem is caused by a typo because you have:

console.log(link.onlick);// onlick !!

Instead of:

console.log(link.onclick);

Here's the full code:

var link = document.createElement("a");
      var ce = function (e) {
        alert("A");
      }
link.onclick = ce; // Or link.addEventListener("click", ce);
link.text="Click me!!";
document.body.appendChild(link);
console.log(link.onclick);// here you will get function (e) { alert("A"); }

And now it works fine, here's a DEMO.

Upvotes: 1

wildavies
wildavies

Reputation: 1317

You need to add the link that you create to the DOM before you bind the onclick event.

Once you do this you will no longer get undefined for the log of the onclick event.

var link = document.createElement("a");
var ce = function (e) {
    alert("A");
}
// Add link to page 
document.body.appendChild(link);
link.onclick = ce; // Or link.addEventListener("click", ce);
console.log(ce);
console.log(link.onclick);

Upvotes: 1

Related Questions