1

I'm creating a responsive menu and I'm working on a function that close the menu when a user click outside it, so when a user click any other part of website ( of course, if the menu is open ). All seems to be very easy and there are 2 functions:

1st) Close the menu when any part of html is clicked

$('html').click(function () {

if (jQuery("#responsive_header").hasClass("tvda_header responsive")) {

document.getElementById("responsive_header").className = "tvda_header";

}

});

2nd) Open the menu when the menu's button is clicked

$('#h_r3').click(function () {

var x = document.getElementById("responsive_header");

if (x.className === "tvda_header") { x.className += " responsive"; }

});

Both functions work but there is a conflict between it. When I click the button to open the menu (div id="h_r3") the div class "tvda_header" change to "tvda_header responsive" and is detected by 1st function that of course change it again to "tvda_header" by removing the "responsive" class.

I try to change the order of functions or to run the 2nd after the first by using trigger but without success.

Any suggestion?

wrkman
  • 100
  • 1
  • 12

1 Answers1

1

Stop the propagation of the event in the button click using event.stopPropagation()

$('#h_r3').click(function (event) {
   event.stopPropagation()
   var x = document.getElementById("responsive_header");

   if (x.className === "tvda_header") { x.className += " responsive"; }

});
charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • That's it! Thank you very much @charlietfl, it works! – wrkman May 24 '18 at 23:50
  • just some explanation. Your "h_r3" click also triggers your "html" click, So to avoid that "stopPropagation" is used. By definition "event.stopPropagation() Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event." I hope this helps you understand better – Muhammad Waqas Iqbal May 25 '18 at 00:00
  • Thank you @Muhammad Waqas Iqbal for your details and thank you again charlietfl for your solution. For some strange reason this not work on iPhone by using Safari/Chrome but with Android devices work. Any idea? – wrkman May 27 '18 at 12:06
  • I am not sure but this link might be helpful to you. https://stackoverflow.com/questions/14795944/jquery-click-events-not-working-in-ios?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – Muhammad Waqas Iqbal May 27 '18 at 15:00