Reputation: 813
I tried to increment the value of current 'top' property value within a foreach.
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
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
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
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