Curtis Blackwell
Curtis Blackwell

Reputation: 3207

I'm having difficulty with jQuery's $(selector).each()

Example here: http://jsfiddle.net/KyW6c/2/

I have an ordered list. Each list item is a project in my portfolio. I'm writing some jQuery that will move a clicked list item up to the top left of the ordered list. I've accomplished this, but the problem I'm encountering is that the list items below the clicked one are shifting. This code is provided in the fiddle (commented out).

The solution I'm attempting to implement will set each list item's position to absolute and left and right to it's current position within the ordered list once the page is loaded. I don't know if I'm having trouble because I misunderstand what .each() does, or just how to implement it.

Thanks.

EDIT: The problem is that each list item's left and top values are being set to 0, so they're all just overlapping on at the top left. If you uncomment the jQuery, you'll see the problem.

EDIT 2: I discovered that if I don't set the position to absolute at the same time that I set the left and top properties, it works properly.

Upvotes: 4

Views: 2370

Answers (3)

ltiong_dbl
ltiong_dbl

Reputation: 3216

The problem was as you iterated through each element, you were setting 'postion:absolute' which was removing the current element from the positioning. As each element is "removed" from the layout, the following element floats to the 0,0 position.

By iterating from the bottom up, you're able save the left/top first, then apply postion:absolute without affecting the next element:

  $($('.project').get().reverse()).each(function(){
    var pos = $(this).position();
    $(this).css({
      left: pos.left + 'px',
      top: pos.top + 'px',
      position: 'absolute',
      'z-index': '999'
    })
  });

  // your original code
  $('.project').click(function(){
    var $this  = $(this),
        left = $this.position().left + 'px',
        top  = $this.position().top + 'px';
    $this.css({
      left:      left,
      top:       top,
      position:  'absolute',
      'z-index': '999'
    }).animate({
      left:       0,
      top:        0,
      width:      '750px'
    }, 'fast', 'swing')
  }); 

Upvotes: 2

Curtis Blackwell
Curtis Blackwell

Reputation: 3207

http://jsfiddle.net/KyW6c/11/

Got it figured out with a little help from a friend. Thanks, Matt!

Upvotes: 1

thecodeparadox
thecodeparadox

Reputation: 87073

$('.project').ready().each(..)

should be

$('.project').each(..)

you can try something like this:

  var left = 0,
      top = 0;
$('.project').each(function(){
    var $this  = $(this),
    $this.css({
      left:      (left+10) + 'px',
      top:       (top+10) + 'px',
      position:  'absolute',
      'z-index': '999'
    })
  });

Upvotes: 0

Related Questions