aryanknp
aryanknp

Reputation: 1167

Javascript modal onclick not working on mobile

The problem is in mobile , that the modal is not closing when clicking on the background , I have tried click and click touchstart none of them worked.I have not placed the dropdown inside modal because it is the part of header.I am trying this on safari .

the html part:

<div class="dropdown">
  
    <button class="dropbtn" onclick="showloc()" ><i class="zmdi zmdi-gps-dot" style="color:#555;margin-right:6px;"></i>Location 
      <i class="zmdi zmdi-chevron-down" style="color:#555;"></i>
</br>
<?php echo $locality; ?>
    </button>
    <div class="dropdown-content">
   <h3>Where do you want the delivery?</h3>
 <form class="locform" action="/action_page.php" autocomplete="off">
    <input type="text" id="fname" name="firstname" placeholder="Enter your delivery location">
  </form>

    </div>
  </div> 

<div id="myModal" class="modal"></div>

the javascript code:

var modal = document.getElementsByClassName('modal')[0];
var dc=document.getElementsByClassName('dropdown-content')[0];

function showloc(){

if(dc.style.display == "none"){
dc.style.display = "block";
modal.style.display="block";
}
else{
dc.style.display = "none";
modal.style.display="none";
}
}
window.addEventListener('click',function(){

if(event.target == modal){
modal.style.display="none";
dc.style.display="none";
}


});

the styling part:

    .modal {
    
      display:block;
      position: fixed; 
      z-index: 1; 
      padding-top: 50px; 
      left: 0;
      top: 0;
      width: 100%; 
      height: 100%; 
      overflow: auto; 
      background-color: rgb(0,0,0); 
      background-color: rgba(0,0,0,0.4); 
    }
.dropdown {
  float: left;
  overflow: hidden;
}
.dropdown .dropbtn {
  color: #555;
  text-decoration: none;
  padding: 15px 20px;
margin-top:3px;
  position: relative;
  display: inline-block;
  float:right;
font-size:17px;
}
   
.dropdown .dropdown-content {
  display: block;
  position: absolute;
  background-color: white;
  min-width: 400px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 70;
  text-align: center;
padding:20px;
margin-top:70px;
}

Upvotes: 1

Views: 815

Answers (1)

francovici
francovici

Reputation: 546

The 'click' event won't trigger the listener on Mobile, because there's no click.

You should try "touchend". If I were you, I woul'd add an event listener for click and one for touchend so it works on both mobile and desktop.

Upvotes: 2

Related Questions