Monday, October 13, 2014

Javascript to Simulate Shaking an Object

I know this is trivial but also fun at the same time. Just in case you need something fun for your school projects. You need to modify it to suit your need as the codes in the following is very minimal:


<html>
<script>

var x = 10;
var y = 10;
var myTimer;

function startshake() {
 setTimeout(function() {moveElemX("shakeObject",x-(Math.floor(Math.random()*6)));},10);
 setTimeout(function() {moveElemX("shakeObject",x+(Math.floor(Math.random()*7)));},25);
 setTimeout(function() {moveElemX("shakeObject",x-(Math.floor(Math.random()*5)));},40);
 setTimeout(function() {moveElemX("shakeObject",x+(Math.floor(Math.random()*6)));},55);
 setTimeout(function() {moveElemX("shakeObject",x-(Math.floor(Math.random()*8)));},70);
 setTimeout(function() {moveElemX("shakeObject",x);},85);
 setTimeout(function() {moveElemY("shakeObject",y-(Math.floor(Math.random()*7)));},15);
 setTimeout(function() {moveElemY("shakeObject",y+(Math.floor(Math.random()*3)));},35);
 setTimeout(function() {moveElemY("shakeObject",y-(Math.floor(Math.random()*5)));},45);
 setTimeout(function() {moveElemY("shakeObject",y+(Math.floor(Math.random()*7)));},65);
 setTimeout(function() {moveElemY("shakeObject",y-(Math.floor(Math.random()*5)));},80);
 setTimeout(function() {moveElemY("shakeObject",y);},95);
}


function stopshake() {
 clearInterval(myTimer);
 document.getElementById(elemName).style.top = y+"px";
 document.getElementById(elemName).style.left = x+"px";
}

function moveElemX(elemName,X) {
 document.getElementById(elemName).style.left = X+"px";
}

function moveElemY(elemName,Y) {
 document.getElementById(elemName).style.top = Y+"px";
}


</script>
<body>

<span id="shakeObject" style="position:absolute;top:10px;left:10px">
<table bgcolor="#ffff22" cellpadding=2 cellspacing=2 align=center valign=middle><tr><td>Telephone</td></tr></table>
</span>

<script>
myTimer = setInterval("startshake()",1000);
</script>

<br><br><br>
<a href="javascript:stopshake()">Stop Shaking</a>
</body>

</html>


This is just an example. There are still many other ways to do it. You can also change the timer or offset to other values that suit your need. Hope you like it!

No comments:

Post a Comment