April 19, 2011

Best way to do a horizontal scrolling pane in jQuery?

Question by CaptSaltyJack

I came up with the solution below. It works great, but I’m curious to know if there’s a more efficient way of doing it. Thanks!

HTML:

<div id="magic-pane" style="width: 300px; height: 400px; background: #eee; overflow: hidden">
    <div id="scroller" style="width: 600px; height: 100%; left: 0px; position: relative">
        <div id="pane1" style="width: 300px; height: 100%; background: #efe; float: left">
            <span id="pane1-clicker">Whee, click me!</span>
        </div>
        <div id="pane2" style="width: 300px; height: 100%; background: #fee; float: left">
            <span id="pane2-clicker">Whoosh! Click me!</span>
        </div>
    </div>
</div>

Script:

$(document).ready(function() {
    $('#pane1-clicker').click(function() {
        $('#scroller').animate({ left: '-300px' }, 500);
    });
    $('#pane2-clicker').click(function() {
        $('#scroller').animate({ left: '0' }, 500);
    });
});

So basically, the magic-pane is a small viewport that’s 300px wide. Inside it is a scroller that’s twice as wide and contains two divs side-by-side. Pretty simple, but again, just wondering if there’s a more efficient way of coding this.

Demo

Answer by Starx

When the number are minimum, you do not need to worry about anything. Like in you case, 2 is pretty manageable. Note: that you are writing separate onClick function for all the pane, which will create problem.

But as the number grow, lets say 50, then you will have to write different onClick functions of $('#pane1-clicker') …. $("#pane50-clicker), which is highly inefficient. You should modify your script, to support any number of panes, without writing extra codes.

  • Also, extend the function, so that it can be used as plugin.
  • It would be better if the plugin could match a particular selector and assign the related positions like left:300px

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!