Clicking on outside the div unable to close the toggle bar menu in iphone

Issue

I have written code to close menu when clicking on outside the div on mobile devices.It is working on Android phones but it is not working in IOS devices.

If i click on toggle bar dropdown menu will be opened and if i click on the menu or outside the menu div menu should be closed.It is working fine for Android getting problem in IOS devices.

This is the javascript code i have added.

        window.onclick = function(event) {
        if (!event.target.matches('.dropbtn')) {
         var dropdowns = document.getElementsByClassName("dropdown-content");
         var i;
         for (i = 0; i < dropdowns.length; i++) {
         var openDropdown = dropdowns[i];
         if (openDropdown.classList.contains('show')) {
         openDropdown.classList.remove('show');
       }
       }
       }
       }


        <div class="container">
        <nav class="navbar menu-bar navbar-inverse navbar-fixed-top">
        <div class="container-fluid">
        <div class="navbar-header">      
        <button onclick="myFunction()" type="button" class="navbar-toggle dropbtn" data-toggle="collapse" data-target="#myNavbar">
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>                        
        </button>
        <a class="navbar-brand" href="#"><img src="images/Bezelsoft.png" class="img-responsive"></a>
          </div>
          <div class="collapse navbar-collapse dropdown-content" id="myNavbar" >    
     <ul class="nav navbar-nav navbar-right">
     <li class="active"><a href="index.html">HOME</a></li>
    <li><a href="service.html">TECHNOLOGY SERVICES</a></li>
    <li><a href="industries.html">INDUSTRIES</a></li>
    <li><a href="carporate.html">CORPORATE</a></li>
    <li><a href="resources.html">RESOURCES</a></li>
    <li><a href="contact.html">CONTACT US</a></li>
  </ul>
</div>
</div>
</nav>
 </div>    

Solution

Click event for the body will not work on safari based devices. you can create a clickable area and make it cusrsor: pointer or another solution is use touchevents.

document.addEventListener('touchend', function(e){
    // your event body here 
}, false);

In your code, it should be :

document.addEventListener('touchend', function (event) {
    if (!event.target.matches('.dropbtn')) {
        var dropdowns = document.getElementsByClassName("dropdown-content");
        var i;
        for (i = 0; i < dropdowns.length; i++) {
            var openDropdown = dropdowns[i];
            if (openDropdown.classList.contains('show')) {
                openDropdown.classList.remove('show');
            }
        }
    }
    event.preventDefault();
}, false);

Answered By – Wellwisher

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published