Search code examples
jqueryhtmlcss-positionoverlapping

Make div overlap the adjacent two divs and stretch to 100% width on click?


So I have 3 div columns (33% width each) and I'm trying to set it up so that once any column is clicked on, it will expand to 100% width and at the same time, overlap the two columns next to it.

I know it's something to do with z-index and positioning of the divs but I guess it needs to be added to the Jquery rather than the CSS?

The left div is overlapping the middle and right divs on click, but can't get the other two to do the equivalent. On click, they stretch to 100% but drop below the left column and don't overlap. See the fiddle...

Fiddle here - http://jsfiddle.net/PGRAr/7/

Here's the Jquery that stretches the column on click:

$('#divleft, #divmid, #divright').toggle(function(){
$(this).animate({height:'200', width: '100%'})
}, function() {
$(this).animate({height:'200', width: '33.3%'})
})

And here's the CSS:

#divleft{
width:33.3%;
height:200px;
background:#ccc;
margin-top: 10px;
float: right;
position: absolute;
}

#divmid{
width:33.3%;
height: 200px;
background: #696;
margin-top: 10px;
float: right;
}

#divright{
width:33.3%;
height:200px;
background:#000;
margin-top: 10px;
float: right;  
}

Left column works perfectly, I just need to create the same effect for the middle and right columns...

Thanks!


Solution

  • I had to do some minor modifications to your CSS and added some JS, but this should get you started.

    $('#divleft, #divmid, #divright').toggle(function () {
    
        //Set a base config option that you can modify
        var cfg = { height: '200', width: '100%' };
    
        //Set current element as top-most div
        $(this).css({ 'z-index': 100 });
    
        //Get the pct of the current element and switch based on it.
        var pct = $(this).css('left').split('p')[0] / $(document).width();
        if (pct <= .33 && pct > 0) {
            cfg.left = '0';
            $(this).data('oldLeft', "33%");
        } else if (pct <= .66 && pct > .33) {
            cfg.left = '0';
            $(this).data('oldLeft', "66%");
        }
        $(this).animate(cfg)
    }, function () {
        var cfg = { height: '200', width: '33%', 'z-index': 1 };
        if ($(this).data('oldLeft')) {
            console.log($(this).data('oldLeft'));
            cfg.left = $(this).data('oldLeft');
        }
        $(this).animate(cfg)
    })
    

    Here is the working fiddle