Hey ya’ll
Last days I have the necessity to develop some work in html, using javascript and css and a lot more stuff. It’s been funny to be honest, I’m feeling pumped doing this kind of stuff, looks like I am 5 years in the past
.
One thing that I never did before was to create a mouse wheel functionality in JS, thing that I was used to do in Actionscript.
Well, it is pretty straight forward, also I could easily save this code for future reuse, after some implementation, obviously.
I have tested this code in a couple browsers, looks like it is working pretty smooth.
/**
* @author Marcelo Duende
*
* This is a MouseWheel utility which allows you to scroll your content in any browser
*
* The license is FREE it does mean FREEEEEEE!
*
* Contact
* marceloduende.com
* marceloduende.com/blog
* marcelo.duende@gmail.com
*
*/
/**
* Adding event listener
*/
if (window.addEventListener)
window.addEventListener('DOMMouseScroll', wheelHandle, false); /** Mozilla. */
window.onmousewheel = document.onmousewheel = wheelHandle; /** IE - Opera. */
/**
* Handling div
*/
function handlingDelta(delta){
/** kill default actions.*/
if (event.preventDefault)
event.preventDefault();
event.returnValue = false;
document.getElementById("your_elemet_here").scrollTop += -delta*2; /**throw your element there to start the mouse wheeling*/
}
/**
* Handling Delta value
*/
function wheelHandle(event){
var deltaValue = 0;
if (!event) /** For IE. */
event = window.event;
if(event.wheelDelta){ /** IE - Opera. */
deltaValue = event.wheelDelta/120;
if(window.opera) /** Opera 9. */
deltaValue = -deltaValue;
} else if(event.detail){/** Mozilla. In Mozilla delta is multiple of 3 */
deltaValue = -event.detail/3;
}
if (deltaValue)
handlingDelta(deltaValue);
}
Also, you need a html for this, I’ll copy and paste my code quickly, as the focus of this post, is to teach only the JS.
- marcelo
- duende
- marcelo
- duende
- marcelo
- duende
- marcelo
- duende
- marcelo
- duende
And the CSS.
@charset "UTF-8";
/* CSS Document */
.center_div{
width:50%;
height:100px;
margin:auto;
position:relative;
overflow-y:hidden;
overflow-x:auto;
}
#scroll_window ul{
list-style-type:none;
height:50px;
width:200px;
margin:auto;
}
#scroll_window li{
float:left;
padding:20px;
}
#test ul{
list-style-type:none;
height:50px;
width:200px;
margin:auto;
}
#test li{
float:left;
padding:20px;
}
#test ul a:hover {
color: #000000;
}
#test ul a{
text-decoration:none;
color:#FF0000;
}
great info
Great Article!