[javascript] 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.

This question is related to javascript events new-operator element add

The answer is


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.


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.


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

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

Not sure but try :

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

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


JQuery:

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

or:

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

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(); });


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.


You can also set attribute:

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to events

onKeyDown event not working on divs in React Detect click outside Angular component Angular 2 Hover event Global Events in Angular How to fire an event when v-model changes? Passing string parameter in JavaScript function Capture close event on Bootstrap Modal AngularJs event to call after content is loaded Remove All Event Listeners of Specific Type Jquery .on('scroll') not firing the event while scrolling

Examples related to new-operator

Java FileOutputStream Create File if not exists How to add to an existing hash in Ruby Expression must have class type Why should C++ programmers minimize use of 'new'? Creating an object: with or without `new` int *array = new int[n]; what is this function actually doing? Open button in new window? How to open in default browser in C# Print in new line, java Deleting an object in C++

Examples related to element

How can I loop through enum values for display in radio buttons? How to count items in JSON data Access multiple elements of list knowing their index Getting Index of an item in an arraylist; Octave/Matlab: Adding new elements to a vector add item in array list of android GetElementByID - Multiple IDs Numpy ValueError: setting an array element with a sequence. This message may appear without the existing of a sequence? Check if one list contains element from the other How to get the focused element with jQuery?

Examples related to add

Add a new item to recyclerview programmatically? momentJS date string add 5 days How to add an object to an ArrayList in Java ListView with Add and Delete Buttons in each Row in android How to add new column to MYSQL table? How to add text to an existing div with jquery Datetime in C# add days How to add hours to current time in python How To Add An "a href" Link To A "div"? How to use ArrayList.addAll()?