Koiski Koiski - 24 days ago 7
jQuery Question

Insert div on next line when element is clicked

I am trying to make something similar to what you find in google images. When a picture is clicked, a div with the image appears on the next line over the other images that is under the clicked one.

I have a set of divs with float:left and position:relative. They have different widths. When i click on a div i want a new full width div to appear on the next line. The divs under the clicked one should be bushed down under the full width one.

I tried to do this by looping through the divs and compare the position of the divs to the clicked one like this:

$(".Wrapper").on("click", ".testDivs", function () {
var thisTop = $(this).position().top;
$(".testDivs").each(function(i, obj) {
var otherTop = $(obj).position().top;
if(thisTop < otherTop){
$(".fullWidthDiv").insertBefore(obj);
return;
}
});
});


This doesn't work and I don't really know how I should do this. Any tips/solutions?

Answer

Ended up making a solution based on my initial code. This doesn't require all the CSS the other solution that was postet suggested. Adding rows dynamically was also suggested, but this became very complicated when making it responsive to window resizing. Feel free to reply if you have any comments on this

 function positionDiv() {
    var checker = false;    
    var n;                
    var thisTop = clickedElement.position().top;   

    $(".testDivs").each(function(i, obj) {
        var otherTop = $(obj).position().top;  

        if(thisTop < otherTop){
            $(".testDivs:eq(" + (i-1) + ")").after($(".fullWidthDiv")); 
            checker = true;
            return false;        
        }
        n = i;                   
    });

    if (!checker) {
        $(".testDivs:eq(" + n + ")").after($(".fullWidthDiv"));
    }
}


var clickChecker = null;
$(".wrapper").on("click", ".testDiv", function () {
    if (clickChecker === this){
        $(".fullWidthDiv").hide();
        clickChecker = null;
    } else {
        $(".fullWidthDiv").show();
        clickChecker = this;
    }

    clickedElement = $(this);

    positionDiv();
});

window.onresize = function(event) {
    if( clickedElement != null) {
        $(".tagTextWrapper").hide();
        positionDiv();
        $(".tagTextWrapper").show();
    }
}