0

I'm using a resize function to wrap a div with a container when the browser width is less than 801px or the height is greater than the width. My problem is when either of those become true then the div gets wrapped with the selector 8 times. What am I doing wrong?

Here is my code:

$(document).ready(function(){
 function wrapperWidth() {
  var wrapper_width = $('body').width();
   if (wrapper_width < 801 || window.innerHeight > window.innerWidth) {
      $('.video-profile').wrap("<div></div>");
   }
 }
 wrapperWidth();
 $(window).resize(function() {
wrapperWidth();
 });
});

When the the browser width becomes less than 801px I get this.

<div>
 <div>
  <div>
   <div>
    <div>
     <div>
      <div>
       <div>
        <div class="video-profile"></div>
       </div>
      </div>
     </div>
    </div>
   </div>
  </div>
 </div>
</div>
double-beep
  • 5,031
  • 17
  • 33
  • 41
Pollux Khafra
  • 862
  • 5
  • 17
  • 32

1 Answers1

3

Browsers can fire the resize event multiple times during a resize operation, see this question for more details.

I suggest checking for presence of the container to avoid duplicates:

if (wrapper_width < 801 || window.innerHeight > window.innerWidth) {
    if (!$('.video-profile').parent().hasClass('vp-container')) {
        $('.video-profile').wrap("<div class="vp-container"></div>");
    }
}
Community
  • 1
  • 1
Jer
  • 610
  • 5
  • 9