0

I am building responsive menu. I want to show Menu button, when I am under 1100px, and for above i show normal horizontal menu. I first check $(window).width() and if width is less than 1100px I trigger some events, and if not then another.

My Menu button (for under 1100px) has click event. When I first have windows above 1100px (for example 1300px) and then resize for mobile, this click event does not work.

It works only when I reload my page.

$(document).ready(function() {
  if($(window).width() < 1100) {
    $('.menu-button').click(function(e) {
      $('#menu-body').slideToggle();  
      $(this).parent().siblings().children().children().removeClass('active');
    });

    $('.menu-top').click(function(e) {
      $(this).parent().siblings().children().removeClass('active');
      $(this).siblings().addClass('active');
    });

  } else {
    $('.menu-top').mouseover(function(e) {
      $(this).parent().parent().children().children().removeClass('active');
      $(this).siblings().addClass('active');
      $(this).parent().addClass('active-top');
    });

    $('.menu-point').mouseleave(function(e) {
      $(this).removeClass('active-top');
      $(this).children().removeClass('active');
    });
  }
});
Umbro
  • 1,984
  • 12
  • 40
  • 99
lukpar
  • 27
  • 5

1 Answers1

0

The problem is that you're setting the click/mouse event listeners only when the document finishes loading ($(document).ready). This is called after the page is done loading, and after refresh.

You'll need to call this code again whenever the windows size passes the breakpoint in either direction.

jQuery on window resize

In your case,

function foobar() {
    if($(window).width() < 1100) {
        $('.menu-button').click(function(e) {
            $('#menu-body').slideToggle();  
            $(this).parent().siblings().children().children().removeClass('active');
        });

        $('.menu-top').click(function(e) {
            $(this).parent().siblings().children().removeClass('active');
            $(this).siblings().addClass('active');
        });
    } else {
        $('.menu-top').mouseover(function(e) {
            $(this).parent().parent().children().children().removeClass('active');
            $(this).siblings().addClass('active');
            $(this).parent().addClass('active-top');
        });

        $('.menu-point').mouseleave(function(e) {
            $(this).removeClass('active-top');
            $(this).children().removeClass('active');
        });
    }
}
$(document).ready(foobar);
$(window).on('resize', foobar);
Ivan Rubinson
  • 3,001
  • 4
  • 19
  • 48