Odd animate behaviour

Hi there,

So I’m working on a kind of picture gallery thingy. There are 7 images in a grid, and one is featured. The featured image has a ratio of 2:3, or 3:2. All of the non-featured images are square (1:1).

It’s probably simpler if you just use the code to see what I mean…


<!DOCTYPE>

<html>
<head>
	<style>
		#gallery{
			position:relative;
			width:400px;
			height:300px;
		}

		.grid-item{
			font-size:2em;
			margin:0 5px 5px 0;
			width:95px;
			height:95px;
			background:red;
			position:absolute;

			-webkit-transition: width 0.6s;
			-webkit-transition: height 0.6s;
		}

		.featured{
			width: 295px;
			height: 195px;
		}

		.featured.port{
			width:195px;
			height:295px;
		}
	</style>

	<script src="http://code.jquery.com/jquery-latest.js"></script>
	<script>
		$(document).ready(function(){

			function drawGrid(){
				var $gridItems = $('.grid-item').not('.featured');

				var $featured = $('.featured'), featuredLeft = 100, layoutMatrix = [0, 4, 8, 9, 10, 11], j=0;

				if($featured.hasClass('port')){
					layoutMatrix = [0, 1, 4, 5, 8, 9]
					featuredLeft = 200;
				}

				for(i in layoutMatrix){

					if(layoutMatrix[i] < 4){
						var top = 0;
					}

					else if(layoutMatrix[i] < 8){
						var top = 100;
					}

					else{
						var top = 200;
					}

					var left = (layoutMatrix[i]%4) * 100;

					$gridItems.eq(j).animate({left:left, top:top}, 500);

					$featured.animate({top:0, left:featuredLeft}, 500);

					j++;
				}
			}

			$('.grid-item').click(function(){

				$('.featured').removeClass('featured');
				$(this).addClass('featured');

				drawGrid();
			});

			drawGrid();
		});
	</script>
</head>

<body>
	<div id="gallery">
		<div class="grid-item featured">1</div>
		<div class="grid-item port">2</div>
		<div class="grid-item">3</div>
		<div class="grid-item">4</div>
		<div class="grid-item port">5</div>
		<div class="grid-item port">6</div>
		<div class="grid-item">7</div>
	</div>
</body>

</html>

The idea is that the grid resizes and re-shuffles itself on click. Which to be fair it does. Except (most of the time) the image which was featured, doesn’t animate at the same time as all the others. It waits until everything else has moved, then slides into position.

Is this a bug with jQuery, or should I be approaching this in a different way?

Many thanks,
Mike

Sorry guys, this is becoming a bit of a habit…

I solved the problem by adding .stop(true, true) before each animate method.

:rolleyes:

Hi,

Just a tip: you can also this code instead of .stop(true, true), to prevent selecting elements that are being animated in the first place.

.filter(':not(:animated)')

It generally makes for a smoother experience.

Here’s a comparison of the two techniques: http://css-tricks.com/full-jquery-animations/