Add onclick event to newly added element in JavaScript

JavascriptEventsNew OperatorElementAdd

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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

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

instead.

Solution 2 - Javascript

You can also set attribute:

elem.setAttribute("onclick","alert('blah');");

Solution 3 - Javascript

Not sure but try :

elemm.addEventListener('click', function(){ alert('blah');}, false);

Solution 4 - Javascript

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

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

Solution 5 - Javascript

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.

Solution 6 - Javascript

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.

Solution 7 - Javascript

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

Solution 8 - Javascript

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.

Solution 9 - Javascript

JQuery:

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

or:

elemm.attr("onclick", "alert('Hi!')");

Solution 10 - Javascript

In case you do not want to write all the code you have once written in the function you called. Please use the following code, using jQuery:

> $(element).on('click', function () { add_img(); });

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDesolatorView Question on Stackoverflow
Solution 1 - JavascriptkennytmView Answer on Stackoverflow
Solution 2 - JavascriptbonafernandoView Answer on Stackoverflow
Solution 3 - JavascriptBoris DelormasView Answer on Stackoverflow
Solution 4 - JavascriptMinhNguyenView Answer on Stackoverflow
Solution 5 - JavascriptDavid HedlundView Answer on Stackoverflow
Solution 6 - JavascriptGuillaume LebourgeoisView Answer on Stackoverflow
Solution 7 - JavascriptbresleveloperView Answer on Stackoverflow
Solution 8 - Javascriptcrazy2beView Answer on Stackoverflow
Solution 9 - JavascriptAlexView Answer on Stackoverflow
Solution 10 - JavascriptPrateekView Answer on Stackoverflow