user2421594
user2421594

Reputation: 81

Inserting div after and before on window resize

I want to take each div with class of top and insert inside the div with a class of .blurb...Problem is that it adds too many repeated elements and crashes the page..Here is a code below

<div class="top">top1</div>
<div class="top">top2</div>
<div class="top">top3</div>

<div class="blurb">
    <p>Blurb Copy</p>
    <p>Blurb Copy</p>
    <p>Blurb Copy</p>
</div>

<div class="blurb">
    <p>Blurb Copy</p>
    <p>Blurb Copy</p>
    <p>Blurb Copy</p>
</div>

<div class="blurb">
    <p>Blurb Copy</p>
    <p>Blurb Copy</p>
    <p>Blurb Copy</p>
</div>
function sizeUpdate() {
    var width = $(window).width(); // Get window width
    var height = $(window).height(); // Get window height

    $('.top').each(function(){
        if (width < 993) {        
            $(this).insertAfter('.blurb');
        } else if (width > 992) {
            $(this).insertBefore('.blurb');
        }
    });
};  

$(document).ready(sizeUpdate); // When the page first loads
$(window).resize(sizeUpdate); // When the browser changes size

Upvotes: 0

Views: 596

Answers (3)

Lawrence Johnson
Lawrence Johnson

Reputation: 4043

Assuming all three tops to each blurb, you could do this:

$('.blurb .top').remove();
$('.top').each(function() {
    var __top = $(this);
   if (width < 993) {        
        $(this).clone(true).insertAfter('.blurb');
    } else if (width > 992) {
        $(this).clone(true).insertBefore('.blurb');
    }
});

Basically, just clear the blurb tops before adding them. I also added the clone property, because assuming you want to add these and not just move them, you'll need duplicates of the original.

Upvotes: 0

Vitaliy Gorbenko
Vitaliy Gorbenko

Reputation: 490

I suppose you are trying to achieve this:

    $('.top').each(function(index){
    if (width < 993) {        
        $(this).insertAfter($('.blurb')[index]);
    } else if (width > 992) {
        $(this).insertBefore($('.blurb')[index]);
    }
});

Upvotes: 1

stackoverfloweth
stackoverfloweth

Reputation: 6917

var canInsert = true;

 $('.top').each(function(){
        if (width < 993 && canInsert) {        
            $(this).insertAfter('.blurb');
            canInsert=false;
        } else if (width > 992 && canInsert) {
            $(this).insertBefore('.blurb');
            canInsert=false;
        }

        setTimeout(function(){
            canInsert = true;
        }, 500);
    });

Upvotes: 0

Related Questions