118

I have been trying to add onclick event to new elements I added with JavaScript.

The problem is when I check document.body.innerHTML I can actually see the onclick=alert('blah') is added to the new element.

But when I click that element I don't see the alert box is working. In fact anything related to JavaScript is not working..

here is what I use to add new element:

function add_img() { 
  var elemm = document.createElement('rvml:image'); 
  elemm.src = 'blah.png';
  elemm.className = 'rvml';
  elemm.onclick = "alert('blah')";
  document.body.appendChild(elemm);
  elemm.id = "gogo";
  elemm.style.position='absolute';
  elemm.style.width=55;
  elemm.style.height=55;
  elemm.style.top=200;
  elemm.style.left=300;
  elemm.style.rotation=200; 
}

Here is how I call this function:

<button onclick=add_img()>add image</button>

Now the image draws perfectly inside the browser. But when I click the image I don't get that alert.

Brett DeWoody
  • 59,771
  • 29
  • 135
  • 184
Desolator
  • 22,411
  • 20
  • 73
  • 96
  • 2
    Oh the beauty of jQuery. Maybe this will be helpful in the future :) $('.rvml').live('click', function() { alert(1); }); – Daniel Sloof Jul 23 '10 at 07:45

9 Answers9

235

.onclick should be set to a function instead of a string. Try

elemm.onclick = function() { alert('blah'); };

instead.

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
  • Fantastic! But now, suppose I want the handler to take an argument? If I put the argument (an Object, say) in `elemn.onclick = function(foo) {myHandler(foo.bar);};`, when I get to `myHandler`, it's as if the argument was never there. – Tim Erickson Apr 03 '22 at 04:31
  • 1
    @TimErickson you can use the `this` keyword inside the function to access element. For example `elem.onclick = function () { alert(this.id);}` – sketchyTech Jun 06 '22 at 09:19
59

You can also set attribute:

elem.setAttribute("onclick","alert('blah');");
bonafernando
  • 1,048
  • 12
  • 14
35

Not sure but try :

elemm.addEventListener('click', function(){ alert('blah');}, false);
Boris Delormas
  • 2,509
  • 1
  • 19
  • 27
12

you can't assign an event by string. Use that:

elemm.onclick = function(){ alert('blah'); };
WillardSolutions
  • 2,316
  • 4
  • 28
  • 38
MinhNguyen
  • 182
  • 2
6

Short answer: you want to set the handler to a function:

elemm.onclick = function() { alert('blah'); };

Slightly longer answer: you'll have to write a few more lines of code to get that to work consistently across browsers.

The fact is that even the sligthly-longer-code that might solve that particular problem across a set of common browsers will still come with problems of its own. So if you don't care about cross-browser support, go with the totally short one. If you care about it and absolutely only want to get this one single thing working, go with a combination of addEventListener and attachEvent. If you want to be able to extensively create objects and add and remove event listeners throughout your code, and want that to work across browsers, you definitely want to delegate that responsibility to a library such as jQuery.

David Hedlund
  • 128,221
  • 31
  • 203
  • 222
  • 1
    I need this only for internet explorer.. the short one works like charm. thanks for the detailed solution though – Desolator Jul 23 '10 at 07:59
2

I don't think you can do that this way. You should use :

void addEventListener( 
  in DOMString type, 
  in EventListener listener, 
  in boolean useCapture 
); 

Documentation right here.

Guillaume Lebourgeois
  • 3,796
  • 1
  • 20
  • 23
2

cant say why, but the es5/6 syntax doesnt work

elem.onclick = (ev) => {console.log(this);} not working

elem.onclick = function(ev) {console.log(this);} working

bresleveloper
  • 5,940
  • 3
  • 33
  • 47
0

You have three different problems. First of all, values in HTML tags should be quoted! Not doing this can confuse the browser, and may cause some troubles (although it is likely not the case here). Second, you should actually assign a function to the onclick variable, as someone else meantioned. Not only is this the proper way to do it going forward, but it makes things much simpler if you are trying to use local variables in the onclick function. Finally, you can try either addEventListener or jQuery, jQuery has the advantage of a nicer interface.

Oh, and make sure your HTML validates! That could be an issue.

crazy2be
  • 2,134
  • 1
  • 21
  • 17
  • I'm using this locally. so It wont be a problem for me.. about jQuery I didn't like because I cannot take control of everything and its just messy with lots of codes and it impacts with other javascript libraries. I would prefer to build my own library rather than wasting my time to figure out how to use jQuery. thanks for your help though :) – Desolator Jul 23 '10 at 08:08
0

JQuery:

elemm.attr("onclick", "yourFunction(this)");

or:

elemm.attr("onclick", "alert('Hi!')");
Alex
  • 73
  • 1
  • 8
  • That code should throw loud warnings to you. Also, can you add some explanation to it such that others can learn from it? What does `elem` contain? – Nico Haase Oct 12 '18 at 09:53
  • And if you've read the most upvoted answer, you would also have written code using an anonymous function to avoid just this problem – Nico Haase Oct 13 '18 at 08:07