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.
Attaching the event dynamicallyclassName = 'dynamic-link'; // Class name li. innerHTML = dynamicValue; // Text inside $('#links'). appendChild(li); // Append it li. onclick = dynamicEvent; // Attach the event!
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.
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.
.onclick
should be set to a function instead of a string. Try
elemm.onclick = function() { alert('blah'); };
instead.
You can also set attribute:
elem.setAttribute("onclick","alert('blah');");
Not sure but try :
elemm.addEventListener('click', function(){ alert('blah');}, false);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With