0

I have a click event for my hamburger menu. To position this menu correctly I have used a couple variables. My only problem is when the screen size changes I need to update the values of these variables so that the menu always stays in the correct position. I have tried using a jQuery(window).resize function to reset the values but its not working and I don't get why.

jQuery("#button").click(function(){
    var nav = jQuery("#nav_container");
    var head_h = jQuery('#fullhead_wrap').height();
    var nav_height = jQuery(window).height() - head_h;

    jQuery(window).resize(function(){
        var new_head_h = jQuery('#fullhead_wrap').height();
        head_h = new_head_h;

        var new_nav_height = jQuery(window).height() - new_head_h;
        nav_height = new_nav_height;
    });

    jQuery("#button span").toggleClass("open");
    jQuery("body").toggleClass("overflow");
    jQuery('.header_nav li').toggleClass('link_fall');
    nav.toggleClass('menu_open');

    nav.height(nav_height);

    if(nav.hasClass('menu_open')){
        nav.css('top', head_h);
    }else{
        nav.css('top', '0');
    }
});
2
  • Make a fiddle or something for people to take a look. Commented Apr 13, 2018 at 8:54
  • 1
    Every time you click on #button you install a new resize event listener. That crashes. Also try with html,body instead of window. Commented Apr 13, 2018 at 8:57

1 Answer 1

1

The problem is that, you have nested resize event in click event. You should separate it to get it work.

var variables_which_are_used_by_both_events; //...
// put this variables here such as nav_height and head_h
// In some cases it's better to update their value in each event 

jQuery(window).resize(function(){
    var nav = jQuery("#nav_container");
    var head_h = jQuery('#fullhead_wrap').height();
    var nav_height = jQuery(window).height() - head_h;
});

jQuery("#button").click(function(){
    var nav = jQuery("#nav_container");
    var head_h = jQuery('#fullhead_wrap').height();
    var nav_height = jQuery(window).height() - head_h;
   // your code...
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.