0

I would like to display a "receptacle" after each 3 divs that are visible. Because following the filter each div is hidden or not.

I want the receptacle just after each 3 divs... but if the articles ends by one or two on the line just put a receptacle after them.

Ex: html

<div class="container">
    <article style="display:block"></article>
    <article style="display:block"></article>
    <article style="display:none"></article>
    <article style="display:block"></article>
    <article style="display:none"></article>
    <article style="display:block"></article>
    <article style="display:block"></article>
    <article style="display:none"></article>
    <article style="display:block"></article>
    <article style="display:block"></article>
</div>

js

jQuery(document).ready(function ($) {

    $('.container > article:visible:nth-child(3n)').after('<div class="receptacle"></div>');

    $('article').each(function () {
        $(this).on('click', function () {
            $(this).nextAll('receptacle').text('toto');
        });
    });

});

css

article {
    float:left;
    width:30%;
    height:40px;
    background:DeepSkyBlue;
    margin:5px;
}

the fiddle: http://jsfiddle.net/XLK6z/

Thanks!

  • Here's a fiddle that better shows what's happening. http://jsfiddle.net/isherwood/XLK6z/2 – isherwood Sep 03 '13 at 18:30
  • http://stackoverflow.com/questions/2175694/jquery-nth-child-that-is-currently-visible should help with your problem. It looks like it does the nth-child selector is applied first and then the visible. So the `div` is only getting inserted after visible nth childs. – Danny Sep 03 '13 at 18:42

3 Answers3

1

Looks like nth-child is "applied" to .container > article and not to .container > article:visible. Then you may filter "manually":

var $visible = $('.container > article:visible');
$visible.each(function(idx) {
    if (idx % 3 === 2 || idx === $visible.length - 1) {
         $(this).after('<div class="receptacle"></div>');
    }
});
kirilloid
  • 14,011
  • 6
  • 38
  • 52
1

The problem is with your CSS. Everything works fine, but you're floating the articles around.

http://jsfiddle.net/isherwood/XLK6z/6

article {
    display: inline-block;
}

Oh, I did add a dot to your receptacle selector in the click function.

isherwood
  • 58,414
  • 16
  • 114
  • 157
0

Here's one that works: http://jsfiddle.net/XLK6z/8/

$(document).ready(function() {
    $(".container article").each(function(){
        if ($(this).is(":visible")){
            if ($(this).prevAll("article:visible").length%3 === 2  || $(this).is(":last-child")) {
                $(this).after('<div class="receptacle"></div>');
            }
        }
    });
});
andi
  • 6,442
  • 1
  • 18
  • 43