Reputation: 475
i have an absolutely positioned div with children. I want this divs top position to change every x seconds. I have tried with jquery setInterval
but it only changes once. Below is my code.
.com_prices {
width: 100%;
height: 100%;
overflow: hidden;
background: #dd0d0d;
position: relative;
}
.com_tabs {
position: absolute;
height: auto;
width: 100%;
}
.com_price_tab {
width: 90%;
margin: 10px auto;
height: 100px;
background: #fff;
}
The html
<div class="com_prices">
<div class="com_tabs">
<div class="com_price_tab"></div>
<div style="background: #28bc88" class="com_price_tab"></div>
<div style="background: #fff000" class="com_price_tab"></div>
<div style="background: #333" class="com_price_tab"></div>
<div style="background: #28bc88" class="com_price_tab"></div>
<div style="background: #999" class="com_price_tab"></div>
<div class="com_price_tab"></div>
<div class="com_price_tab"></div>
</div>
</div>
The script
setInterval(function() {
$('.com_tabs').animate({top: "-100px"}, 350);
}, 2000);
Upvotes: 1
Views: 1007
Reputation: 8137
You're setting top equal to "-100px". You need to get the current position subtract 100.
var $comtabs = $('.com_tabs');
setInterval(function() {
var top = parseInt($comtabs.css("top"));
$comtabs.animate({top: top - 100 + "px"}, 350);
}, 2000);
Working example:
var $comtabs = $('.com_tabs');
setInterval(function() {
var top = parseInt($comtabs.css("top"));
$comtabs.animate({
top: top - 100 + "px"
}, 350);
}, 2000);
html,
body {
background: #000;
height: 100%;
margin: 0;
padding: 0;
}
.com_prices {
width: 100%;
height: 100%;
overflow: hidden;
background: #dd0d0d;
position: relative;
}
.com_tabs {
position: absolute;
height: auto;
width: 100%;
}
.com_price_tab {
width: 90%;
margin: 10px auto;
height: 100px;
background: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="com_prices">
<div class="com_tabs">
<div class="com_price_tab"></div>
<div style="background: #28bc88" class="com_price_tab"></div>
<div style="background: #fff000" class="com_price_tab"></div>
<div style="background: #333" class="com_price_tab"></div>
<div style="background: #28bc88" class="com_price_tab"></div>
<div style="background: #999" class="com_price_tab"></div>
<div class="com_price_tab"></div>
<div class="com_price_tab"></div>
</div>
</div>
Upvotes: 2
Reputation: 1114
The problem is that you're setting the top
position to -100px. After the first time the function is trying to set the top position to be the same value it's already at (-100px) and thus not making any change.
You could get the current top value and subtract 100px from the value. Something like:
setInterval(function() {
var $el = $('.com_tabs');
var top = $el.css('top');
var topNumber = top.substr(0, top.length -2) - 100;
console.log(topNumber);
$el.animate({top: topNumber + 'px'}, 350);
}, 2000);
Upvotes: 1