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?
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?
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
top be undefined? and 2) what is the significance of (+top)?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>
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);
});
$('div')returns a HTMLCollection which is not exaclty as Array, as you might be thinking.forEachis a Array method