Caelan Grgurovic Caelan Grgurovic - 5 months ago 51
jQuery Question

wrap() duplicates element more than once - jQuery

I have a pretty basic function which allows me to wrap a div tag, inside of another div tag, whenever the browser window becomes larger than x amount of pixels.

However, I have a strange bug which occurs once the page is resized more than once.

For starters, I'll show you the jQuery script which I am currently using, so you can get a better idea of what I am working with.

$(window).on("resize", function(){
if (window.matchMedia("(min-width: 1920px)").matches) {
$(".navbar-inner").wrap("<div id='center'></div>");
} else {
var content = $("#center").contents();
$("#center").replaceWith(content);
}
}).trigger("resize");


Basically, once the window becomes larger than
1919px
, it will force the navbar to be wrapped inside of a new div tag.

The problem with this is when the page is resized more than once, the
<div id='center'>
element will be duplicated multiple times.

So, rather than the output in the dom being something like:

<div id="center">
<div class="navbar-inner">
<!-- e.t.c... !-->
</div>
</div>


It will be:

<div id="center">
<div id="center">
<div id="center">
<div id="center">
<!-- this will duplicate over and over until at some point, it displays the navbar-inner div !-->
<div class="navbar-inner">
<!-- e.t.c... !-->
</div>
</div>
</div>
</div>
</div>


I have searched almost every single thread, link, answer I could find, but I simply cannot find something that will fix my issue.

I'm pretty new to JavaScript, so all help is appreciated.

Cheers.

Answer

You need to check inside if condition that it's already wrapped or not by checking the count of element. Also you can use unwrap() to unwarp the element.

$(window).on("resize", function() {
  if (window.matchMedia("(min-width: 1920px)").matches) {
    if (!$('#center').length)
      $(".navbar-inner").wrap("<div id='center'></div>");
  } else {
    $("#center .navbar-inner").unwrap();
  }
}).trigger("resize");   

or check the parent is #center using is() method.

$(window).on("resize", function() {
  if (window.matchMedia("(min-width: 1920px)").matches) {
    if (!$(".navbar-inner").parent().is("#center"))
      $(".navbar-inner").wrap("<div id='center'></div>");
  } else {
    $("#center .navbar-inner").unwrap();
  }
}).trigger("resize");
Comments