<script>
function moverFoto(){
$('#janela').animate({left:"-200"},1000);
}
$( function(e) {
setInterval(moverFoto,500);
});
</script>
The setInterval only runs once and for
<script>
function moverFoto(){
$('#janela').animate({left:"-200"},1000);
}
$( function(e) {
setInterval(moverFoto,500);
});
</script>
The setInterval only runs once and for
Actually what you're doing is throwing the element to left -200. Since the second time it is already in this position you do not notice the function running again.
An example of the code so that you notice the function running multiple times is as follows:
var pLeft = parseInt($('#janela').css("left")); // Pega a posição atual do elemento em relação a esquerda da tela.
function moverFoto(){
$('#janela').animate({left:pLeft},1000);
pLeft -= 5; // A cada execução remove 5 pixels da posição atual
console.log("Posição atual: " + pLeft); // Código que mostra no console a posição do elemento a cada looping
}
setInterval(moverFoto,500);
Understanding the concept, just set your animation to the appropriate values.
Example in JSFiddle: link
It is not that setInterval
is only executed 1 time. It is that when you change the position of the element to -200px with animate()
, the next time you call it, it will not do anything because the element will already be in the -200px position.
You can use the method callback to return the element to the home position. Example:
function moverFoto(){
$('#janela').animate({left:"0"},1000, function(){
$(this).css("left", "500px");
});
}
$( function(e) {
setInterval(moverFoto,500);
});
#janela{
width: 100px;
height: 100px;
background: red;
left: 500px;
position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="janela">janela</div>
Now, the ideal would be to use setTimeout
instead of setInterval
, because the setInterval
time may not be synchronized with animate()
time:
function moverFoto(){
$('#janela').animate({left:"10"},1000, function(){
$(this).css("left", "500px");
setTimeout(moverFoto,500);
});
}
$( function(e) {
setTimeout(moverFoto,500);
});
#janela{
width: 100px;
height: 100px;
background: red;
left: 500px;
position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="janela">janela</div>
You can also use your own css for animation and put it as infinite you only need to call the function once with setTimeout
function moverFoto() {
$("#janela").addClass("animar");
}
$(function(e) {
setTimeout(moverFoto, 500);
});
#janela {
width: 100px;
height: 100px;
background: red;
left: 0;
position: relative;
}
.animar {
animation: andar 2s infinite;
animation-fill-mode: forwards;
}
@keyframes andar {
0% {
left: 0;
opacity: 9;
}
70% {
opacity: 9;
}
100% {
left: 500px;
opacity: 0;
}
}
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script><divid="janela"></div>