Thursday, June 10, 2010

A simple slideshow using mouse wheel

A JavaScript event for developers to take advantage of that- the "onmousewheel" event. As its name suggests, this event fires whenever the user rotate the mouse wheel either upwards or downwards, most commonly to scroll a webpage, "onmousewheel" is supported in IE6, Opera9+, Safari2+, and Firefox1+, though in FF (as of FF3.x), the equivalent "DOMMouseScroll" should be used, as "onmousewheel" as an event name isn't yet recognized.
Lets start a tour with onmusewheel event:

<img id="slideshow" src="1.jpg" />

<script type="text/javascript">
    var myimages=["1.jpg","2.jpg", "3.jpg"];
    var slideshow=document.getElementById("slideshow");
    var nextslideindex=0;

    function rotateimage(e)
   {
        //equalize event object
        var evt=window.event || e;
     
       //delta returns +120 when wheel is scrolled up, -120 when scrolled down
        var delta=evt.detail? evt.detail*(-120) : evt.wheelDelta;
       
       //move image index forward or back, depending on whether wheel is scrolled down or up
        nextslideindex = (delta<=-120)? nextslideindex+1 : nextslideindex-1;
       
       //wrap image index around when it goes beyond lower and upper boundaries
        nextslideindex = (nextslideindex<0)? myimages.length-1 : (nextslideindex>myimages.length-1)? 0 : nextslideindex;

        slideshow.src=myimages[nextslideindex];
        if (evt.preventDefault)
        {//disable default wheel action of scrolling page
            evt.preventDefault();
        }
       else
      {
         return false;
       }

   }

//FF doesn't recognize mousewheel as of FF3.x
var mousewheelevt=(/Firefox/i.test(navigator.userAgent))? "DOMMouseScroll" : "mousewheel";

if (slideshow.attachEvent) //if IE (and Opera depending on user setting)
    slideshow.attachEvent("on"+mousewheelevt, rotateimage)
else if (slideshow.addEventListener) //WC3 browsers
    slideshow.addEventListener(mousewheelevt, rotateimage, false)
</script>

Note the use of preventDefault() and return false to disable the default mouse wheel action when the cursor is over the image, which is to scroll the page.

No comments:

Post a Comment