简体   繁体   中英

why is jquery resize not working?

I am making a responsive menu. I put the code to change the menu in a function called file. when the document or the window are resized Jquery call the function file again to change the menu. but that does not work. when I load the page it works but on resize it don't.

Jquery:

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

file();
function file(){
  if(width <= 400){
      $('.link').remove();
      $('head').append('<link class="link" rel="stylesheet" href="nav2.css">');
  }else if(width >400){
      $('.link').remove();
      $('head').append('<link class="link" rel="stylesheet" href="nav.css">');

  }else{
      alert('error');
  }
}
$(window).resize(function(){
  file();
});

$(document).resize(function(){
  file();
});

can somebody help me with fixing this problem

Your width variable isn't going to change once it's set. You should move that inside the function declaration.

function file(){
  var width = $(window).width();
  if(width <= 400){
    $('.link').remove();
    $('head').append('<link class="link" rel="stylesheet" href="nav2.css">');
  }else if(width >400){
    $('.link').remove();
    $('head').append('<link class="link" rel="stylesheet" href="nav.css">');
 }else{
  alert('error');
 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM