Learn how to easily make horizontal anchors with jQuery
I've got a freelance job from a Brazilian company few days ago. The project is fine, nothing so different than the usual. Except for one thing: They want the page to scroll horizontally.
The clients are getting creative these days...
My biggest problem is the main menu: If the page would be normal I could use anchor. But I can't since anchors don't work on the horizontal.
Fortunatelly the solution is easy: .scrollLeft()
What .scrollLeft() does is simple: It returns the position of the horizontal scroll bar. And if we pass a parameter it will set the scroll bar where we want.
I have an example on how it's done. Let's walk through it:
HTML
Very simple, no problem at all. Only one navigation and a couple of divs just to give something to work with:
<header> <nav> <ul> <li><a class="nav-item1" href="#">Item 1</a></li> <li><a class="nav-item2" href="#">Item 2</a></li> <li><a class="nav-item3" href="#">Item 3</a></li> </ul> </nav> </header> <section> <div class="item item1">Item 1</div> <div class="item item2">Item 2</div> <div class="item item3">Item 3</div> </section>
CSS
The CSS is very basic, just to give some formatting:
<style type="text/css"> nav { position: fixed; z-index: 1030; } section { width: 3600px; top: 100px; position: relative; overflow: auto; } .item{ float: left; position: relative; width: 900px; height: 500px; font-size: 200px; } .item1 { background: #f00; } .item2 { background: #0f0; } .item3 { background: #00f; } </style>
Javascript
Since we have 3 items I've created a function which groups everything. In that way I am able to keep the code clean, without repeating important parts:
function horizontalNavigation(position, event) { $('html').scrollLeft(position); event.preventDefault(); }
And here is where the magic happens:
$('.nav-item1').click(function (event) { horizontalNavigation(0, event); }); $('.nav-item2').click(function (event) { horizontalNavigation(900, event); }); $('.nav-item3').click(function (event) { horizontalNavigation(1800, event); });
There is only one problem with this code: What if I want to have a smoothly horizontal scrolling? For that we can use .animate(). Solution in bold bellow:
function horizontalNavigation(position, event) { $('html').animate({scrollLeft: position}, 800);
event.preventDefault(); }
As you can see it is not so complicated as it looks. Just a bit of work, but quite easy.