Thursday, 1 October 2020

Append on resize and load with multiple instances

I want to append .item from .left to .right on page load and resize when $(window).width() < 479. The problem is that with multiple instances, the resize function re-iterates to append .item several times.

How do I change the code so that it only executes once per .item?

codepen.io/moofawsaw/pen/PoNVejV

function moveDiv() {
  if ($(window).width() < 479) {
    $('.item').appendTo('.right');
  } else {
    $('.item').appendTo('.left');
  }
}
moveDiv();
$(window).resize(moveDiv);
body {
  display: flex;
}

.post {
  display: flex
}

.item {
  height: 100px;
  width: 100px;
  border: 2px solid;
}

.right,
.left {
  min-width: 100px;
  height: 200px;
}

.right {
  background: silver;
}

.left {
  background: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="post">
  <div class="right">
    <div class="item"></div>
  </div>
  <div class="left"></div>
</div>
<div class="post">
  <div class="right">
    <div class="item"></div>
  </div>
  <div class="left"></div>
</div>


from Append on resize and load with multiple instances

No comments:

Post a Comment