user1131277
user1131277

Reputation: 11

.scrollLeft() in div

I would like a div to .scrollLeft() to the .next() image every time I click the "next" link.

it works fine if I have the document scroll (jsfiddle) but if I want the div to scroll it becomes all wacky. (jsfiddle)

Upvotes: 0

Views: 5517

Answers (3)

dku.rajkumar
dku.rajkumar

Reputation: 18568

I don't think you need to do that much for it, I would suggest you to use slides plugin or cycle pluging, which will be the best way to do it according to me. Check the example on the plugin sites.

One more good plugin for this carousel

Upvotes: 0

Alec Gorge
Alec Gorge

Reputation: 17390

offset() doesn't include the amount that the div is already scrolled. You need to account for that.

See the jsfiddle.

I also made it so that the scrolling operates based on a index in the array as opposed to making a jQuery method call. This makes it execute (a little bit) faster.

Upvotes: 5

Kevin Reid
Kevin Reid

Reputation: 43733

Note that .offset() is relative to the document — this means that it depends on where the div is scrolled to already!

I'm not sure of the best thing to do instead (DOM position properties are hairy and lacking things that ought to be simple), but one that works is to use .position() instead, and establish an offset parent within the scrollable element (that is, an element which is relatively positioned and contains the images).

Changes to your code:

 $("#slides").animate({scrollLeft: $($current).position().left}, 500);
    <div id="slides">
        <div class="offset-parent"> <!-- added -->
            <img src="http://www.petwebsite.com/uploadpics/ginger-cat.jpg" class="images" alt="cat">
            ...
        </div>
    </div>
.offset-parent {
    position: relative;
}

jsfiddle

Upvotes: 2

Related Questions