jQuery: calculating slide dimensions on responsive slideshows

jQuery: calculating slide dimensions on responsive slideshows

How to calculate slide dimensions on responsive slideshows.

Responsive slideshows are interesting: if you try to use the width(), outerWidth(), innerWidth() jQuery's methods, a 0 value is what you'll get for the dimensions of each slide. Even more interesting is the fact that the object returned by the JavaScript's getBoundingClientRect() will show a 0 value for its width property. This is because we're working with fluid slideshows.

Consider the following CSS rules:


body {
	margin: 0;
	padding: 0;
}

#slider {
	margin: 2em auto;
	max-width: 960px;
	overflow: hidden;
}

#slides {
	margin: 0;
	padding: 0;
	list-style: none;
	max-height: 300px;
	width: 30000px; /* Overridden later by jQuery */
	position: relative;
}

#slides li {
	float: left;
	max-width: 960px;
	position: relative;
	max-height: 300px;
	display: block;
}

The max-width property affects only the box model of the specified element but from a pure JavaScript perspective this means that the computed value will be 0. Now imagine this: we want to override the original width of the main wrapper to allow our slideshow to have a width equal to the total width of its slides.

As we said, earlier, we have to follow another approach:


var setWidth = function( element ) {
	var $slides = $( options.slides, element ),
		total = 0,
		$wrapper = $( options.wrapper, element );
				
		$slides.each(function() {
			var bounding = this.getBoundingClientRect();
			var left = bounding.left;
			var right = bounding.right;
			var bodyWidth = $( "body" ).width();
			var totalWidth = bodyWidth - ( left + right );
				
				
				
			total += totalWidth;
				
		});
			
		$wrapper.width( total );
};

We've simply subtracted the sum of the left and right offset of the element from the total width of our page. You can see the demo on this page.