This script should cyclically show and hide the menu when the button is pressed:
$(".menu-btn:first").click(switchMenu); function switchMenu(){ var menu = $(".menu:first"); if (!menu.hasClass('menu-show')){ menu.addClass('menu-show'); } else { menu.removeClass('menu-show'); } }; I get into if (i.e., not else ) each time I press a button, and not every other time. With the help of alert I made sure that after adding the menu-show class, the menu-show variable is not updated. Why is that?
- This script is located immediately after the HTML code (suppose I am so comfortable in this task).
- Outside, the
addClassandremoveClassfunctions work, which means that there is no error in the rows with these methods. - I read several sources, but did not clearly understand what the difference between
switchMenu()andswhitchMenu. It was experimentally established that in this script, when changingswitchMenutoswitchMenu()function is invoked without pressing a button, the menu is shown, and after pressing the button, the program is moved toelse. I absolutely do not understand what is happening. - But the most interesting thing: if after the function
switchMenu()addmenu.removeClass('menu-show');then theGoogleChromedebugger, of course, willUncaught ReferenceError: menu is not definederrorUncaught ReferenceError: menu is not defined, but the button will work correctly!
Please explain the behavior of this script.
Update And here is the reason: the function following switchMenu() . This function ( switchMenu ) removes the menu only when the button is pressed, and the function indicated below, when clicked outside the menu, to any place.
$(function($){ $(document).mouseup(function (e){ var menu = $(".menu"); if (!menu.is(e.target) && menu.has(e.target).length === 0) { $(".menu").removeClass('menu-show'); } }); });