Skip to content Skip to sidebar Skip to footer

Script That Change The Width Of Multiple Divs With The Same Class Name

After gotten help from @michael-p who had made a script that works excellent, i was looking for some code that could work better in my new situation (old topic link). The 'contain

Solution 1:

JS FIDDLE

Change the id of container to a class, and then just iterate over each container class. You'll also need to change the scope of your maxOffsetRight var then from global to only applying to each iteration of container.

$('.container').each(function(){
    var maxOffsetRight = 0;
    var currentOffsetRight - 0;
    $(this).children().each(function(index) {
       currentOffsetRight = $(this).position().left + $(this).outerWidth(true);
       if (currentOffsetRight > maxOffsetRight) {
           maxOffsetRight = currentOffsetRight;
       }
    });

    $(this).css('width', maxOffsetRight);
})

Solution 2:

The script I wrote for your previous question was designed for the case you presented, i.e. with one flexbox container. But it could be easily adapted for a whole set of flexbox containers.

First we will have to change the id to a class, because we will have more than one container. Then, we will iterate on each container, and compute the largest offset right of the flexbox items. Therefore we have to put the variable initialization inside a function iterated on the containers. As follows :

$('.container').each(function() {

    var maxOffsetRight = 0,
        currentOffsetRight;

    // Find the biggest offset right of all childs 
    $(this).children().each(function(index) {
        currentOffsetRight = $(this).position().left + $(this).outerWidth(true);
        if (currentOffsetRight > maxOffsetRight) {
            maxOffsetRight = currentOffsetRight;
        }
    });

   // Set the width of the current container
   var offsetLeft = $(this).position().left;
   $(this).css('width', maxOffsetRight - offsetLeft);                     
});

Note that when setting the width, we have to substract the offsetLeft of the container. Should have done that in the previous version, but didn't notice it as there was only one container, and he was at an offset left of 0.

Fiddle


Post a Comment for "Script That Change The Width Of Multiple Divs With The Same Class Name"