...

View Full Version : Animate a div depending where the mouse is



tomharto
03-06-2012, 09:36 AM
Im wanting to make a div move according to where the mouse is IE if the mouse is on the left the div moves right and visa versa. I've got the pixels for where the middle of the screen is but im unsure what to do next.

If anyone can help ill be very grateful, ill try and find an example to help illustrate what i mean.

webdev1958
03-06-2012, 09:40 AM
Post at least your markup to hopefully make things clearer.

Also,
.....if the mouse is on the left..... on the left of what?

tomharto
03-06-2012, 11:17 AM
My markup atm is just literally one centered div



<body>
<div id="MiddleBox" style="width:800px;height:400px; background-color:#CCCCCC;position:absolute;left:50%;margin-left:-400px;">
</div>

</body>


That wasn't very clear was it :p, imagine there was an X in the very middle of the screen, on the left of that.

vwphillips
03-06-2012, 02:25 PM
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
<title></title>
</head>

<body>
<div id="gauge" style="position:absolute;left:0px;top:10px;width:100%;height:0px;">
</div>
<div id="MiddleBox" style="position:absolute;top:100px;width:800px;height:400px; background-color:#CCCCCC;position:absolute;left:50%;">
</div>
<script language="JavaScript" type="text/javascript">
/*<![CDATA[*/

function zxcMove(o){
var oop=this,obj=document.getElementById(o.MoveID),gauge=document.getElementById(o.GaugeID);
obj.style.left=(gauge.offsetWidth-obj.offsetWidth)/2+'px';
oop.obj=obj;
oop.gauge=gauge;
oop.w=obj.offsetWidth/2;
oop.center();
oop.addevt(document,'mousemove','move');
oop.addevt(window,'resize','center');
}

zxcMove.prototype={

move:function(e){
var oop=this,ctr=this.ctr(),w=oop.w,mse=this.mse(e)[0];
if (mse<ctr-w||mse>ctr+w){
oop.obj.style.left=(mse<ctr-w?Math.max(mse,0):Math.min(mse-w*2,oop.gauge.offsetWidth-w*2))+'px';
}
else {
oop.center();
}
},

center:function(){
this.obj.style.left=this.ctr()-this.w+'px';
},

mse:function(e){
if (window.event){
var docs=[document.body.scrollLeft,document.body.scrollTop];
if (!document.body.scrollTop){
docs=[document.documentElement.scrollLeft,document.documentElement.scrollTop];
}
return [e.clientX+docs[0],e.clientY+docs[1]];
}
return [e.pageX,e.pageY];
},

addevt:function(o,t,f,p){
var oop=this;
if (o.addEventListener) o.addEventListener(t,function(e){ return oop[f](e,p);}, false);
else if (o.attachEvent) o.attachEvent('on'+t,function(e){ return oop[f](e,p); });
},

ctr:function(){
return this.gauge.offsetLeft+this.gauge.offsetWidth/2;
}

}

new zxcMove({
MoveID:'MiddleBox',
GaugeID:'gauge'
});
/*]]>*/
</script>
</body>

</html>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum