0

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
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
user2421594
  • 83
  • 1
  • 10

3 Answers3

1

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]);
    }
});
Vitaliy Gorbenko
  • 490
  • 4
  • 14
0
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);
    });
stackoverfloweth
  • 6,669
  • 5
  • 38
  • 69
0

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.

Lawrence Johnson
  • 3,924
  • 2
  • 17
  • 30