Skip to content Skip to sidebar Skip to footer

Wrap And Unwrap Divs Responsively

I have a set of 6 DIVs which I want to wrap in a new div every X divs depending on the screenwidth of the browser. So to start I have

Solution 1:

You can use loop:

var $div= $('#your_id div'),
    length = $div.length;
for (var i = 0; i < length; i = i + 3) {
    $div.slice(i, i + 3).wrapAll('<div class="group" style="display:table-row" />')
}

Like this apply the different script for different resolutions.

Example:

if($(window).width <= 768){
var $div= $('#your_id div'),
        length = $div.length;
    for (var i = 0; i < length; i = i + 2) {
        $div.slice(i, i + 2).wrapAll('<div class="group" style="display:table-row" />')
    }
}

But I suggest you go through the bootstrap to build your website responsive. http://getbootstrap.com/

Update: to unwrap when resize:

$(window).on('resize',function() {
  //to unwrap 
  $('.group').contents().unwrap();
  //now use other codes here to wrap
});

Solution 2:

You can get the screen size with jquery and also there is a resize function for handling screen size changes - e.g:

$(window).resize(function() {
    $(window).height();
    $(window).width();
});

You can write a function that gets all divs with jquery and then iterates through them adding your display style every nth time where n is determined by screensize at load or resize.


Post a Comment for "Wrap And Unwrap Divs Responsively"