0

I'm using floated divs in a grid, and I want to fill out the last row so it always has = number. The function should work with any number of items in each row (since this may vary). I got everthing working accept it only generates one filler, not two (as wanted in example below)!

html:

<ul>
 <!-- first row -->
 <li>Item 1</li>
 <li>Item 2</li>
 <li>Item 3</li>
<!-- second row -->
 <li>Item 4</li>
 <li>Item 5</li>
 <li>Item 6</li>
<!-- third row -->
 <li>Item 7</li>
</ul>

css:

li.gallery-item { width: 33.3334%; float: left;}

js:

function rowFillers() {
        var $galItem = jQuery('.gallery-item'), 
            $rowFiller = jQuery('<div class="row-filler">TEST</div>')
            $lisInRow = 0;

        //Calculate number of gallery-items on each row
        $galItem.each(function() {
            $this = jQuery(this);
            if($this.prev().length > 0) {
                if($this.position().top != $this.prev().position().top) return false;
                $lisInRow++;
            } else {
                $lisInRow++;
            }   

        });

        //Calculate number in last row
        var $lisInLastRow = $galItem.length % $lisInRow;
        if($lisInLastRow == 0) $lisInLastRow = $lisInRow;

        //If last row isn't full, add fillers
        if ( $lisInLastRow != $lisInRow) {

            function addRowFiller() {
                    $galItem.last().after($rowFiller);
            }


            $fillerI = $lisInRow - $lisInLastRow;

            for (var i = 0; i < $fillerI; i++) {
                            addRowFiller();
            }
        }
    }

    rowFillers();

Here's a fiddle: https://jsfiddle.net/m8xcpdys/1/

1
  • If I drop the .last() function it generates two "fillers" on each except the last one: jsfiddle.net/m8xcpdys/3 Commented Dec 15, 2016 at 10:31

1 Answer 1

1

I came up with

 function rowFillers() {
    var $galItem = jQuery('.gallery-item'), 
        $rowFiller = jQuery('<div class="gallery-item">TEST</div>')
        $lisInRow = 0;
        var $items = $(".gallery-item");
        var addc = 3 -( $items.length %3);

        for(var i = 0; i < addc; ++i){

            $items.parent().append($rowFiller.clone())
        }
    }

and added the class

div.gallery-item { width: 33.3334%; float: left;}
Sign up to request clarification or add additional context in comments.

1 Comment

Actually, just adding changing addRowFiller to : function addRowFiller() { $galItem.parent().append($rowFiller.clone()); }did it!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.