javascriptjquery-clone

Copying contents in a div on windows resize produces duplicates


I'm having a problem with .clone() that produces so many duplicates that it crashes my browser.

Here's my example code:

<div>
 <div class="mobile-top"></div>
 <div class="date">January 22, 2019 - 13:44</div>
</div>
<div>
 <div class="mobile-top"></div>
 <div class="date">December 2, 2018 - 3:10</div>
</div>
<div>
 <div class="mobile-top"></div>
 <div class="date">March 22, 2017 - 1:37</div>
</div>

And my JS code:

$(window).resize(function() {
 if ($(window).width() < 600) {
  $(".date").clone().appendTo(".mobile-top");
 } else {     
  $(".mobile-top").empty();
 };
}).resize();

What I'm trying to do is when a broswer is under 600px, content in the .date element gets moved to the .mobile-top element. What happens is all three .date elements get grouped and moved into .mobile-top on each div and continues duplicating the content until the browser crashes.

What I'm trying to do is move the .date to .mobile-top in each div when screen is under 600px.

Working example of what I've done so far - https://jsfiddle.net/openbayou/f5qwhnp1/


Solution

  • You just do one mistake, that you are cloning. .date inside window.resize which is continuously cloning and appending again and again here is my code this may help you.

    var date = $('.date').html(),
        mobileTop = $('.mobile-top');
        $(window).resize(function() {
            if ($(window).width() < 600) {
                $(mobileTop).html(date);
            } else {     
                $(mobileTop).html('');
            };
        }).resize();