Snorlax
Snorlax

Reputation: 4735

jQuery: animate image to go left and right continuously

I'm trying to get my image to move continuiously back and forth left to right but it keeps going left and never returns right. I'm following a code that I found, I can't seem to find what I'm doing wrong.

http://jsfiddle.net/7kmmxeeg/1/

$(document).ready(function() {
	function firstleft() {
		$(".block.first").animate({"left": "-=100px" }, 1500, "swing", firstright);
	}
	function firstright() {
		$(".block.first").animate({"right": "+=100px" }, 1500, "swing", firstleft);
	}
	firstleft();
});
div.container {
	position:relative;	
	background-color:rgba(149, 187, 206, 0.36);
	height:700px;
	overflow:hidden;
}

div.block {
	height:200px;
	width:200px;
	background-color:blue;
	overflow:hidden;
}

div.block.first	{
	position:absolute;
	left:100px;
	top:300px;
	overflow:hidden;
}

div.block.second {
	position:absolute;
	top:10px;
	left:500px;
	background-color:green;
	overflow:hidden;
}

div.block.third {
	position:relative;
	top:350px;
	left:500px;
	background-color:red;
}

div.block.first img {
	background-size:cover;
	width:400px;
	margin-left:-100px;
}

div.block.second img {
	background-size:cover;
	width:400px;
	margin-left:-100px;
}

div.block.third img {
	background-size:cover;
	width:400px;
	margin-left:-100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
	<div class="block first">
		<img src="img/first.jpg">	
	</div>
	
	<div class="block second">
		<img src="img/second.jpg">
	</div>
	
	<div class="block third">
		<img src="img/third.jpg">
	</div>
</div>

Upvotes: 0

Views: 1325

Answers (1)

Snorlax
Snorlax

Reputation: 4735

ANSWER: Change right to left in the firstright() function.

function firstleft() {
    $(".block.first").animate({"left": "-=100px" }, 1500, "swing", firstright);
}
function firstright() {
    $(".block.first").animate({"left": "+=100px" }, 1500, "swing", firstleft);
}

Updated Fiddle

Upvotes: 1

Related Questions