Mouse wheel handler in Javascript

I found this very very interesting script by Adomas Paltanavičius to determine if you are using mousewheel.

It returns a delta value, +1 or -1, according to scroll direction.

Scroll mouse wheel to see delta here.

I am publishing it here, and very soon I will start to use it to code games, form handlers, and so on.

Meanwhile, check the original script.

It needs some improvements due to some strange delta values on some browsers.

HTML:
  1. <script type="text/javascript">
  2. function handle(delta) {
  3.     var s = delta + ": ";
  4.     if (delta <0)
  5.         s += "down";
  6.     else
  7.         s += "up";
  8.     document.getElementById('delta').innerHTML = s;
  9. }
  10.  
  11. function wheel(event){
  12.     var delta = 0;
  13.     if (!event) event = window.event;
  14.     if (event.wheelDelta) {
  15.         delta = event.wheelDelta/120;
  16.         if (window.opera) delta = -delta;
  17.     } else if (event.detail) {
  18.         delta = -event.detail/3;
  19.     }
  20.     if (delta)
  21.         handle(delta);
  22. }
  23.  
  24. /* Initialization code. */
  25. if (window.addEventListener)
  26.     window.addEventListener('DOMMouseScroll', wheel, false);
  27. window.onmousewheel = document.onmousewheel = wheel;
  28.  
  29. </script>
  30. </head>
  31. <div id="delta">Scroll mouse wheel to see delta here.</div>
  32. </body>
  33. </html>

Do you have an idea about how to use mouse wheel handling? Let me know, and I will (try to) code it.

Improve the blog rating this post
Tell me what do you think about this post. I'll write better and better entries.
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

5 Responses to “Mouse wheel handler in Javascript”

  1. baluvadivel on August 10th, 2006 8:36 am

    Realy very nice. Thank you so much. is it possible to track the speed of click or scroll? I think possible.

  2. Thomas on October 9th, 2007 5:25 am

    not bad … not bad… :D

  3. Chris on January 7th, 2008 7:32 pm

    I believe this is the (somewhat) same code used in games made for ipods.

  4. giallo on March 3rd, 2008 4:05 pm

    [italian, right?]

    bello bello, c’è modo per caso di creare un javascript o qualcosa del genere che mi cambi la direzione di spostamento di una pagina web, in modo che usando la wheel la pagina vada a destra e a sinistra invece che su e giù?
    Sto costruendo un sito in “horizontal way” e mi servirebbe proprio…

  5. Chris Knox on April 7th, 2008 3:21 pm

    Hi.

    Any idea how to get a mouse scroll wheel to make a page move left/right rather than up/down. I know you can do this by pressing extra buttons but I would like to program this straight into my code if possible.

    Thanks.

Leave a Reply