Maybe this can help you? It is JS and must be modified a bit like you want it, but it can be a start:

<script language="javascript">
var mybox;
var myboxstyle;
var schiebx = 1;
var schieby = 1;
var timerid;
var buehnex;
var buehney;
var grenzex;
var grenzey;


function initer() {
mybox = document.getElementById("mobilbox");
myboxstyle = mybox.style;
var BrowserName = navigator.appName;
var BrowserVersion = navigator.appVersion;
//fenster innen maße
if(BrowserName == "Microsoft Internet Explorer") {
buehnex = document.documentElement.clientWidth;
buehney = document.documentElement.clientHeight;
//alert("IE: " + buehnex + " / " + buehney);
}
else {
buehnex = window.innerWidth;
buehney = window.innerHeight;
//alert("FF: " + buehnex + " / " + buehney);
}
//grenzwerte
grenzex = buehnex - (parseInt(myboxstyle.width, 10)) - 3;
grenzey = buehney - (parseInt(myboxstyle.height, 10)) - 3;
}

function startbox() {
window.clearInterval(timerid);
timerid = window.setInterval("schieb()", 10);
//schieb();
}

function stoppbox() {
window.clearInterval(timerid);
}


function schieb() {
initer();
var posx = parseInt( myboxstyle.left, 10);
var posy = parseInt( myboxstyle.top, 10);
//alert("posx: " + posx);
var mynumber = Math.round(Math.random() * 16000000);
var myhex = mynumber.toString(16);



var collaenge = myhex.length;
var nullen = "";
//nullen erzeugen
for(a=collaenge; a<6; a++) {
nullen+="0";
}
myhex = nullen + myhex;



if(posx > grenzex || posx < 0) {
schiebx*=-1;
myboxstyle.background = "#" + myhex; //random(16000000);
}

if(posy > grenzey || posy < 0) {
schieby*=-1;
myboxstyle.background = "#" + myhex; //random(16000000);
}

posx+=schiebx;
posy+=schieby;

myboxstyle.left = String(posx) + "px";
myboxstyle.top = String(posy) + "px";

document.getElementById("parameter").value = posx + " / " + posy + " / " + myhex;


}


</script>

</head>

<body onLoad="initer()" >

<div name="mobilbox" id="mobilbox" style="position:absolute;width:100px;height:100px;left:100px;top:100px;background:#f0f000;border:solid blue 1px">MOBILBOX</div>

<input type="button" value="start" onClick="startbox()" >
<input type="button" value="stopp" onClick="stoppbox()" >
<input type="text" name="parameter" value="" id="parameter">

</body>
</html>