Reputation: 61
I want to make a carousel with Jquery, and the img have variable width.
I know how to calculate multiple img with a FIX width but i don't know how calculate with VARIABLE width for assign a div (in this case sub_container).
This is the example:
<div id="container">
<div id="sub_container" style="width:WIDTH FROM VARIABLE WIDTH OF IMAGES">
<img id="#number" width="200px" src="#">
<img id="#number" width="240px" src="#">
<img id="#number" width="150px" src="#">
<img id="#number" width="500px" src="#">
</div>
</div>
REMEMBER: The Width of container is getting from width of window/browser.
Can you help me? :/
Thank you VERY VERY much! :(
Upvotes: 0
Views: 155
Reputation: 33885
You could do something like this:
$(function() {
var width = 0;
// Get all images in the sub container
$("img","#sub_container").each(function () {
// Add the width of each image
width += $(this).width();
});
// Do whatever you want with the width
$("#sub_container").width(width);
});
Working example: http://jsfiddle.net/DZ9rF/
Upvotes: 1
Reputation: 6528
Try this:
$.fn.sumWidths = function() {
var sum = 0;
this.each(function() {
sum += $(this).width();
});
return sum;
};
Then
$('#sub_container').width( $('#sub_container img').sumWidths() );
Upvotes: 0