views:

38

answers:

2

I am trying to create new div element and then change it`s position with Jquery.But J query effects only first element.I want to change all elements position with different number.

<div class="userList">
<?php $categories = find_category();

    foreach($categories as $category): ?>
<div id="user">
 <img id="<?php echo $category['cat_id']; ?>" src="<?php echo $category['cat_image']; ?>" />
 <a></a>
</div>
 <?php endforeach ;?>
</div>

If I make in Jquery like

 var a= 60;
$(".userList").children().css({'left':a+'px' ,'top':a+'px'});
  a+=60;

This changes all <div id="user"> to <div id="user" style="left: 60px; top: 60px; "> But I need to make first one left:60px top:60px and next one left:120px top:120px.

I also used .each function like

$(".userList").each(function(){

    $("#user").css({'left':a+'px' ,'top':a+'px'});
                a+=60;

                });

But this time only first <div id="user"> changed to <div id="user" style="left: 60px; top: 60px; "> And the other does not effected.

+1  A: 

First, you should be aware that you can not have more than one element on a page with the same ID. You should make user a class instead.

With regard to the issue, you can use an .each() loop, and multiply 60 by the current index (plus one).

This will give you 60, then 120, 180, 240, etc.

var a= 60;
$(".userList").children().each(function( idx ) {
    var position = a * (idx + 1);
    $(this).css({'left': position ,'top': position});
});
patrick dw
A: 

The part where you set the css, is that exactly the code you're using? If so, it looks like each iteration will set a = 60. You need to define it before the start of the loop.

Aaron Hathaway