Caelan Grgurovic Caelan Grgurovic - 5 months ago 10
jQuery Question

if browser window width is more than x, enclose div in new div

I have a fairly simple function I am wanting to implement into my site, where once the browser windows width is more than or equal to x, it will enclose

<div>
a inside of
<div>
b. (Or any other HTML element i.e:
<span>
).

I have pretty basic knowledge of JavaScript and jQuery. But, I still tried to create the script anyway (well parts of it).

This is what I have so far:

var windowWidth = $(window).width();

if(windowWidth > 1919){
$(".navbar").wrap( "<div class='center'></div>" ); // center navbar
}


One of the problems I am facing with this script is that it will not check the window width automatically. Rather, it will only check it once the page has been refreshed.

How would I get around this problem?

Cheers.

Answer

If your code is working fine and the only issue you have is that it does not get called automatically, then below code should solve this problem. Here, I have attached your code to a window resize event, and also triggered it once, so that on page load, the function is executed once automatically. After that, it gets called whenever window is resized.

I have also added an else clause, because I suppose you would want to unwrap the .navbar if the window width decreases below your selected limit. You can use this or omit as per your requirement.

$(window).on("resize", function(){
  var windowWidth = $(window).width();

  if(windowWidth > 1919){
    $(".navbar").wrap( "<div class='center'></div>" ); // center navbar
  }
  else{
    $(".navbar").unwrap();
  }
}).trigger("resize");//window resize