Make image onclick randomly

I am trying to make moving an image randomly using simple javascript. With an onclick event, the location of the image should move according to the random number that is generated.

Here is my code:

<html> <head><title> Move Image </title> <style type="text/css"> #smiley { position: relative; top: 0px; left: 0px; } </style> <script type="text/javascript"> function changeImg() { var x = Math.floor(Math.random()*300); var y = Math.floor(Math.random()*300); var obj = document.getElementById("emotion"); obj.style.top = x + "px"; obj.style.left = y + "px"; obj.onclick= "changeImg();" } </script> </head> <body> <img id="emotion" src="http://www.google.com/images/srpr/logo4w.png" width="42" height="42"> </body> </html> 

Any idea? Thanks!

+4
source share
4 answers
  • You never assign changeImg() <img>

     <img ... onclick="changeImg()"> 
  • The element should be position: absolute if you plan to use top and left .

  • The <img> has an emotion identifier, not a smiley .

  • You do not need to set the <img> onclick property every time the changeImg() function is changeImg() . Once is enough.

+1
source

This works without a built-in script in all browsers

Codepen demo

 var object = document.getElementById('item'); object.onclick=function(){ var x = Math.floor(Math.random()*300); var y = Math.floor(Math.random()*300); object.style.top = x + 'px'; object.style.left = y + 'px'; }; 

HTML

 <img id="item" src="http://...png" /> 

CSS

 #item { cursor: pointer; position: absolute; top: 0px; left: 0px; transition: all 1s; } 
+1
source

You never set the position of an image object. Instead, you set the emoticon to be relative, but the image is emotion.

Try

 #emotion{ position: relative; top: 0px; left: 0px; } 

I would suggest you call a function, not a string literal. Example:

 obj.onclick = changeImg; 
0
source
 <html> <head><title> Move Image </title> <style type="text/css"> #emotion { position: absolute; top: 0px; left: 0px; border:1px solid red;} </style> <script type="text/javascript"> function changeImg() { var x = Math.floor(Math.random()*300); var y = Math.floor(Math.random()*300); var obj = document.getElementById("emotion"); obj.style.top = x + "px"; obj.style.left = y + "px"; } </script> </head> <body> <img id="emotion" src="http://www.google.com/images/srpr/logo4w.png" width="150" height="42" onclick="changeImg()"/> </body> </html> 
-1
source

All Articles