Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add onclick event to newly added element in JavaScript

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.

like image 345
Desolator Avatar asked Jul 23 '10 07:07

Desolator


People also ask

How do you add an event dynamic to an element?

Attaching the event dynamicallyclassName = 'dynamic-link'; // Class name li. innerHTML = dynamicValue; // Text inside $('#links'). appendChild(li); // Append it li. onclick = dynamicEvent; // Attach the event!

How can I trigger a click event in JavaScript?

Trigger Click Event in JavaScript Using click() An element receives the click event when pressed, and a key is released on the pointing device (eg, the left mouse button) while the pointer is within the element. click() is triggered after the down and up mouse events are triggered in that order.

Can we add onclick to div tag?

We can bind a JavaScript function to a div using the onclick event handler in the HTML or attaching the event handler in JavaScript. Let us refer to the following code in which we attach the event handler to a div element. The div element does not accept any click events by default.


3 Answers

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

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

instead.

like image 67
kennytm Avatar answered Oct 06 '22 15:10

kennytm


You can also set attribute:

elem.setAttribute("onclick","alert('blah');");
like image 53
bonafernando Avatar answered Oct 06 '22 15:10

bonafernando


Not sure but try :

elemm.addEventListener('click', function(){ alert('blah');}, false);
like image 33
Boris Delormas Avatar answered Oct 06 '22 15:10

Boris Delormas