Moving an object on mouse wheel scroll event

442 views
asked May 12, 2012 in General by darkshark (1,500 points)
Hi there,

I want to move an object within a web page when I scroll the mouse wheel, i.e when I move the mouse upwards or downwards. How can I do this using JavaScript? Can anyone please help ?
thanks

2 Answers

0 like 0 dislike
answered May 12, 2012 by FixHost (12,380 points)
JavaScript code for handling mouse scroll event.
window.onload = function()
{
  //adding the event listerner for Mozilla
  if(window.addEventListener) document.addEventListener('DOMMouseScroll', moveObject, false);
  //for IE/OPERA etc
  document.onmousewheel = moveObject;
}

function “moveObject”

function moveObject(event)
{
  var delta = 0;
  if (!event) event = window.event;
  // normalize the delta
  if (event.wheelDelta)
  {
    // IE & Opera
   delta = event.wheelDelta / 120;
  }
  else if (event.detail) // W3C
  {
    delta = -event.detail / 3;
  }
  var currPos=document.getElementById('object').offsetTop;
  //calculating the next position of the object
  currPos=parseInt(currPos)+(delta*10);
  //moving the position of the object
  document.getElementById('object').style.top=currPos+"px";
}
0 like 0 dislike
answered May 12, 2012 by moon_tag (1,380 points)
HTML and CSS for object to be scrolled on mouse wheel movement

<div id="object">This block moves as you move mouse wheel.</div>

CSS code:
#object {
font-weight:bold;
background:yellow;
padding:5px;
width:300px;
position:absolute;
left:500px;
top:200px;
}
...