Horizontal Scrolling With Mousewheel
Posted: Mon Jan 06, 2014 11:44 pm
Full Demo - http://jsbin.com/EBapIRIm/1/
I'm sure someone here may want to learn how to initiate horizontal scrolling via mousewheel. I know there's plenty of JQuery plugins out there that do this, but here's a pure Javascript solution.
Marked Up HTML & CSS for this small demo.
I'm sure someone here may want to learn how to initiate horizontal scrolling via mousewheel. I know there's plenty of JQuery plugins out there that do this, but here's a pure Javascript solution.
Marked Up HTML & CSS for this small demo.
Code: Select all
JavaScript: (This must be added after all your html right before your closing body tag)
<style type='text/css'>
body {
margin:0;
width: 100%;
height: 100%;
background: #469;
}
#contain {
display: inline-block;
position: relative;
width: 100%;
height: 100%;
font-family: arial;
color: #fff;
overflow-y: hidden;
overflow-x: scroll;
white-space: nowrap;
}
.box {
display: inline-block;
width: 90%;
height: 100%;
padding: .5em;
border:0;
padding:0;
background: #1d56b1;
}
.box:nth-child(1) {
background: url('http://itsprettyawkward.files.wordpress.com/2011/05/sunny-day.jpg') 100%;
}
</style>
<div id='contain'>
<div class='box'>
<h2>Page 1</h2>
</div>
<div class='box'>
<h2>Page 2</h2>
</div>
<div class='box'>
<h2>Page 3</h2>
</div>
<div class='box'>
<h2>Page 4</h2>
</div>
<div class='box'>
<h2>Page 5</h2>
</div>
<div class='box'>
<h2>Page 6</h2>
</div>
</div>
Code: Select all
<script type='text/javascript'>
(function() {
function scrollMenu(e) {
e = window.event || e;
var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
document.getElementById('contain').scrollLeft -= (delta*40); // Multiplied by 40
e.preventDefault();
}
if (document.getElementById('contain').addEventListener) {
// IE9, Chrome, Safari, Opera
document.getElementById('contain').addEventListener('mousewheel', scrollMenu, false);
// Firefox
document.getElementById('contain').addEventListener('DOMMouseScroll', scrollMenu, false);
} else {
// IE 6/7/8
document.getElementById('contain').attachEvent('onmousewheel', scrollMenu);
}
})();
</script>