Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make image randomly move onclick

I am attempting to make a image move randomly using plain javascript. Upon the event onclick the image location 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? Thank you!

like image 266
user2138152 Avatar asked Nov 03 '22 02:11

user2138152


1 Answers

This one works without inline 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;
}
like image 132
Ronni DC Avatar answered Nov 09 '22 14:11

Ronni DC