Search code examples
javascriptjqueryhtmlcssjscrollpane

jScrollPane (jQuery) scrolling all items in a content pane API at the same time


I need some help with something. I have 3 or 4 jScrollPanes on the same page, something like this creates them:

@foreach (var thing in Model.things)
{
    <div class="scrollPanes">
        <ul>
            <li>Model.Item</li>
        </ul>
     </div>
}

My CSS is like (these panes scroll horizontally):

.scrollPanes
{
    overflow: auto;
    width: 100%;
}

ul
{
    list-style: none;
    height: 50px;
    width: 1000px;
    margin: 0;
    padding: 0;
}

And here is how i initialize the jScrollPane

var settings = { hideFocus: true };
// Notice how all the elements with class "scrollPane" become a jscrollpane
var pane = $('.scrollPanes').jScrollPane(settings);
var api = pane.data('jsp');
api.reinitialise();

So this makes every a scrollPane, and they all work perfectly fine as I'd expect them to.

What I WANT to do is scroll ALL of the elements by an equal increment using jScrollPane().scrollToX(xxx); or jScrollPane().scrollByX(xxx);

When I call the method:

api.scrollByX(200); api.reinitialise();

That works, but it only scrolls the first list, not any after.

I'm seeking to get it to scroll all of them equally, I'd really appreciate any help on this.

Thanks


Solution

  • The reason your original code didn't work is because of how the .data() method works. See http://api.jquery.com/data/: "Returns value at named data store for the first element in the jQuery collection..." When you call pane.data('jsp'), it's only returning the API for the first element in the collection (which is why only the first pane scrolls for you). To run a method on the API for every element in the collection, you'll need to loop through the elements one by one. You can do that by using .each()

    $(".jpanes").each(function() {
        $(this).data("jsp").scrollByX(200);
    });
    

    Or, if you plan to call the APIs repeatedly, you can get an array of the APIs to call whenever you need and then use a for loop.

    // Store an array of APIs for each element
    var apis = $(".jpanes").map(function() {
        return $(this).data("jsp");
    }).get();
    
    // Call an API method for each element
    for (var i = 0, api; api = apis[i]; i++) {
        api.scrollByX(200);
    }