aviate wong
aviate wong

Reputation: 813

increment within a loop to alter css value doesn't work

I tried to increment the value of current 'top' property value within a foreach.

http://jsfiddle.net/fqmnksgL/

var percent = 50;
$('div').forEach(function (obj, i) {
    $(obj).css('top', $(obj).css('top') + percent);
});

Is there anything wrong with my code above?

Upvotes: 0

Views: 210

Answers (3)

Amit Joki
Amit Joki

Reputation: 59292

forEach is part of Array. Use each instead. You can use the function callback to increment the top property of the current element.

var percent = 50;
$('div').each(function() {
    $(this).css('top', function(_, top){ 
        return parseInt(top, 10) + percent;
    });
});

But it doesn't work as you intended. Perhaps you should try something like the other answer, which uses $.fn.prev

Upvotes: 2

Arun P Johny
Arun P Johny

Reputation: 388446

You can try

var percent = 50;
$('div').css('top', function(i, obj) {
  return i * percent;
});
div {
  width: 50px;
  height: 50px;
  background: red;
  position: absolute;
  top: 10px;
  left: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>

Upvotes: 0

madalinivascu
madalinivascu

Reputation: 32354

You can't add percent (%) to px value, you need to convert one of them

var px = 50;
$('div').each(function () {

    $(this).css('top', parseInt($(this).prev().css('top')) + px);
});

http://jsfiddle.net/fqmnksgL/6/

Upvotes: 0

Related Questions