artemean
artemean

Reputation: 855

Toggle element with two different events

I have a menu in page header that gets hidden when page is scrolled down. But it can be opened by clicking a button in the header and closed by clicking outside the menu.

The problem is when you click the button, then click somewhere on the page and scroll up, the menu doesn't show up. I believe this happens because I use two different events to toggle the menu - scrolling and button clicking and they conflict with each other. So I need some conditional sentence that will check the state of the menu, but can't come up with anything. Please suggest a solution.

In this fiddle http://jsfiddle.net/inliner/dpo8nyfe/4/ you can see the menu with Items 1-4. Scroll the page down, click "Show menu", click somewhere on the page, scroll up and the menu is not visible. This is the problem.

$(".btn").click(function () {
  $(".home_body .main_head .main_nav").toggle();
});

$(window).bind('scroll', function() {
     if ($(window).scrollTop() > 91) {
         $('.main_head').addClass('fixed');
         $(".home_body .main_head .main_nav").hide();
     }
     else {
         $('.main_head').removeClass('fixed');
         $(".home_body .main_head .main_nav").show();
     }
});

Upvotes: 0

Views: 61

Answers (1)

gulty
gulty

Reputation: 1076

Check this fiddle: Fiddle

You are having a different code in your HTML you posted than you have in your fiddle. You first need to make sure to always show/hide the menu on scrolling. Your posted code seems to be fine for that so re-add that to the fiddle. Next you have to make sure that you only hide the menu when your are > 91 thats what ur missing.. Heres the code:

var menu = $(".home_body .main_head .main_nav");
$('html').click(function (e) {
  if ($(e.target).attr('class') == 'btn') {
    menu.toggle();
  } else {
    if ($(window).scrollTop() > 91 && $(e.target).attr('class') != 'main_nav') {
        menu.hide();
    }
  }
});

$(window).bind('scroll', function () {
  if ($(window).scrollTop() > 91) {
    $('.main_head').addClass('fixed');
    menu.hide();
  } else {
    console.log('e')
    $('.main_head').removeClass('fixed');
    menu.show();
  }
});

Also make sure to use on('click', function....) instead of click() for a better performance.

Upvotes: 1

Related Questions