onClick on img works but cannot dynamically attach the same even in javascript, what is wrong? -


the following code creates 2 objects, 1 statically defined in html, event works, , 1 defined in javascript not. can done in javascript, wrong?

<!doctype html> <html>   <head>     <script>       function build() {       var img = document.createelement("img");       img.src = "cat.jpg";       img.onclick = "alert('yo')";       document.getelementbyid("quiz").appendchild(img);     return img;    }    </script>   </head>   <body onload="build()">     <div id="quiz">       <img src="trex.jpg" onclick="alert('hello')"></img>     </div>   </body> </html> 

the problem set onclick function string. when define onclick parameter in html give string, can contain javascript code.

when in javascript must define function called when click on image.

you can pass argument function event triggered it. in following case e event.

  img.onclick = function (e){ alert(e); }; 

you can read more javascript formation @ w3c: http://www.w3schools.com/jsref/event_onclick.asp

var img = document.createelement("img");    img.src = "http://thecatapi.com/api/images/get?format=src&type=jpg&size=med";    img.onclick = function(e) {      alert(e);    };    document.body.appendchild(img);
<img onclick="alert('hello')" src="http://thecatapi.com/api/images/get?format=src&type=jpg&size=med" />


Comments

Popular posts from this blog

node.js - Using Node without global install -

How to access a php class file from PHPFox framework into javascript code written in simple HTML file? -

java - Null response to php query in android, even though php works properly -