Link to home
Start Free TrialLog in
Avatar of hankknight
hankknightFlag for Canada

asked on

jQuery: animate to left

In the example bellow, my "Next" button works but my "Previous" button does not work.

I think the problem is in the way that marginLeft is animated.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>

<style type="text/css">

#banner {
 width: 400px;
 height: 200px;
 overflow: hidden;
}

#banner p {
 width: 4800px;
 height: 200px;
 overflow: hidden;
}

#banner p img {
 width: 400px;
 height: 200px;
 overflow: hidden;
 float: left;
}

.bannerPrev {
 visibility: hidden;
}

</style>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">

$(document).ready(function(){


	var position = 1;

	$('.bannerNext').click(function(){
		position++; 
		if(position>1) $('.bannerPrev').css('visibility','visible'); else $('.bannerPrev').css('visibility','hidden');
		if(position>2) $('.bannerNext').css('visibility','hidden'); else $('.bannerNext').css('visibility','visible');
		$('#banner p').animate({marginLeft: Number($('#banner p').css('marginLeft').replace('px', '') - 400) + 'px'}, 900);

	 }); 
	$('.bannerPrev').click(function(){
		position--;
		if(position<2) $('.bannerPrev').css('visibility','hidden'); else $('.bannerPrev').css('visibility','visible');
		if(position<3) $('.bannerNext').css('visibility','visible'); else $('.bannerNext').css('visibility','hidden');
		$('#banner p').animate({marginLeft: Number($('#banner p').css('marginLeft').replace('px', '') + 400) + 'px'}, 900);
	 });
}); 

</script>
</head>
<body>

	<div id="banner">
		<p>
			<img src="http://upload.wikimedia.org/wikipedia/commons/7/7a/TEST%3F.png" alt="" />
			<img src="http://upload.wikimedia.org/wikipedia/commons/thumb/2/27/Gandhi_signature.svg/400px-Gandhi_signature.svg.png" alt="" />
			<img src="http://upload.wikimedia.org/wikipedia/commons/b/b9/Dannylogo.png" alt="" />
		</p>
	</div>

<p>
<input type="button" value="Previous" class="bannerPrev" />
<input type="button" value="Next" class="bannerNext" />
</p>

</body>
</html>

Open in new window

Avatar of mstrelan
mstrelan
Flag of Australia image

Easy solution is to use the jCarousel jquery plugin. Can be configured to do what you want and much more
http://sorgalla.com/jcarousel/
Avatar of hankknight

ASKER

Thanks but no thanks.  That doesn't answer my question.  What is wrong with my code?
ASKER CERTIFIED SOLUTION
Avatar of mstrelan
mstrelan
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial