Question

I have a function that I want to enable depending on my window width, to customize my menu for mobile and ipad windows... it works fine, but when I resize my window the function is not triggred again. let me explain, here is my function Code :

if ($(window).width() < 960) {
    $('.button_menu').css("display", "block");
   $('#bloc_menu').hide();
    $('.button_menu').click(function() {     
          $(this).next().slideToggle();
          return false;
    });

}

else {

    $('#bloc_menu').css("display", "block");
    $('.button_menu').css("display", "none");
}

if the window width is less than 960, then my menu is hidden, ad I have a button appearing, when clicking on the button, the menu appears.

and if my window is larger than 960, then the button is hidden, and my menu is displayed.

I have also some css rules :

#menu{list-style: none;}
.button_menu{display: none}

@media (max-width: 960px) {
#bloc_menu{margin-top: 10px;position: relative;border-top: 1px solid lightgrey;}

I just want to add a window resize listener but I can't find the solution to do it, can anybody help me with this ?

thanks a lot for your help,

Was it helpful?

Solution 2

To avoid it hiding after you have opened it use a flag and toggle it when you click on the button:

  var flag = 0;

  $('.button_menu').click(function() {     
          $(this).next().slideToggle();
          if(flag==0){ 
          flag=1;
          } else {
          flag=0;
          }
          return false;
    });

  $( window ).resize(function() {
    if ($(window).width() < 960) {
    $('.button_menu').css("display", "block");
    if(flag==0){
    $('#bloc_menu').hide();
    }
  }else{
    $('#bloc_menu').css("display", "block");
    $('.button_menu').css("display", "none");
  }
});

OTHER TIPS

You need to use jquery's resize function:

$( window ).resize(function() {


your code...
});

This will trigger your code evertime the window is resized.

$( window ).resize(function() {

    if($(window).width() < 960) {
        $('.button_menu').css("display", "block");
        $('#bloc_menu').hide();
        $('.button_menu').off().click(function() {     
              $(this).next().slideToggle();
              return false;
        });
    }else{
        $('#bloc_menu').css("display", "block");
        $('.button_menu').css("display", "none");
    }
});

The resize function can be called multiple times, so it can add many click event listeners to your button. Once you click it would run all of them.

Place the off() function right before adding the event listener.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top