Web Hosting Geeks | Web Hosting Experts
Need help? Call us 1(866)TOP-HOST

14120 reviews 1680 hosting providers

Questions & Answers

Moving an object on mouse wheel scroll event

May 12, 2012 by darkshark
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 votes
May 12, 2012 by FixHost
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 votes
May 12, 2012 by moon_tag
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;
}