Here is a simple JavaScript function that can be used to move a html element to a random direction in page.
click on the code to select it.
//sets a random absolute position to a html element; receives the html element
function moveElmRand(elm){
elm.style.position ='absolute';
elm.style.top = Math.floor(Math.random()*90+5)+'%';
elm.style.left = Math.floor(Math.random()*90+5)+'%';
}
- In the following example the moveElmRand() function is called when the mouse is over the button.
<button id="btn_test">Catch Me</button>
<script>
//sets a random absolute position to a html element; receives the html element
function moveElmRand(elm){
elm.style.position ='absolute';
elm.style.top = Math.floor(Math.random()*90+5)+'%';
elm.style.left = Math.floor(Math.random()*90+5)+'%';
}
//get the #btn_test
var btn_test = document.querySelector('#btn_test');
//register to call moveElmRand() on mouseover event to #btn_test
btn_test.addEventListener('mouseover', function(e){ moveElmRand(e.target);});
//register click to #btn_test
btn_test.addEventListener('click', function(e){ alert('You are Good.');});
</script>