css – jQuery, given a Variable with DIV with items, how to scroll an Item to the Left – Education Career Blog

I have the following

<div id="big" style="width:100%">
 <div id="slider">
  <div class="item" id="item1"><img src="some50x50.jpg" /></div>
  <div class="item" id="item2"><img src="some50x50.jpg" /></div>
  <div class="item" id="item3"><img src="some50x50.jpg" /></div>
  <div class="item" id="item4"><img src="some50x50.jpg" /></div>


.item {text-align:center;float:left;width:50px;}

The ID=BIG DIV can be of random width, 500px, 800px, etc…based on the browser size

What’d I’d like to be able to do with jQuery is slide an item, like item 3, all the way to the left of the div id=slider.

Where I’m stuck is how to find the offset of the item to know how far to slide.

If would be great if there was a way to say Move item3 all the way to the left of DIV ID Slider…



It’s not the most elegant solution, but this should get you started:

$(function() {
    $('#slide').click(function() {
        var bigLeft = $('#big').position().left;
        var item = $('.item:eq(2)');
        var itemLeft = item.position().left;
        var itemTop = item.position().top;
            position: 'absolute',
            float: 'none',
            display: 'inline',
            top: itemTop,
            left: itemLeft
            'left': bigLeft

Basically, jQuery makes it so that you don’t actually need to know how far to slide your item, you only need to know its final destination. You’ll also have to tinker with the item’s position when you do the animation, since you won’t be able to animate it the way that you want while it’s floating left.

Once you’ve set a firm position for the item, you just need to call .animate() and tell it to animate the item’s left position to match that of your big div’s left position.

Here’s a demo showing this in action: http://jsfiddle.net/Ender/Jbrqh/

Leave a Comment