1

I am learning now how to create popups in mobile devices, and I created a popup that closes when I touch any part of the screen, but it doesn't work on ios (maybe on all touch devices, haven't checked), only on the computer.

Now based on the information I read here:

jQuery click events not working in iOS

Make onclick work on iphone

How to bind 'touchstart' and 'click' events but not respond to both?

Cannot close popup() window in iPhone Safari

The popup opens fine because you press a link attribute <a> to open it up, however upon closing I can press any part of the screen.

Here is the code:

var modal = document.getElementById('myModal'); // Get the popup
var btn = document.getElementById("myBtn"); // Get the button that opens the popup

btn.onclick = function() { // Open the popup 
    modal.style.display = "block";
}

window.onclick = function(event) { // Closes the popup
    if (event.target == modal) {
        modal.style.display = "none";
    }
}

I tried adding cursor: pointer; in CSS, changing the script in javascript to onmouseover instead of click, changing the script, changing window.click to div.click and adding the following code to the javascript script:

let touchEvent = 'ontouchstart' in window ? 'touchstart' : 'click';
window.on(touchEvent, function(event){...});

Nothing worked...

I guess I don't quite get how to use the touch event listener, if it's connected.

C. Arnold
  • 89
  • 1
  • 13

1 Answers1

1

You need to add event listeners for touchstart and/or touchend for this to work on mobile devices, check out the snippet below:

// JavaScript
var modal = document.getElementById('myModal'); // Get the popup
var btn = document.getElementById("myBtn"); // Get the button that opens the popup

btn.onclick = function() { // Open the popup 
    modal.style.display = "block";
}

let eventsArray = ["click","touchstart", "touchend"];

eventsArray.forEach( function(event) { 
    window.addEventListener(event, function(e) {
      if (e.target === modal) {
          modal.style.display = "none";
      }
    }, false);
});
/*CSS*/
body {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
}

#myModal {
  display: none;
  position: fixed;
  top: 0;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(0, 0, 0, 0.25);
  width: 100%;
  height: 100%;
  text-align: center;
}

#myModal span {
  position: fixed;
  top: 50%;
  left: 50%;
  padding: 10px;
  background-color: #a600a6;
  color: #fff;
  transform: translate(-50%, -50%);
}
<!--HTML-->
<body class="overlay">
  <div >
    <button id="myBtn"> 
      Open Modal
    </button>
  </div>
  
  <div id="myModal">
    <span>Hello World!</span>
  </div>
</body>

Tested on jsfiddle with an iPad and it works.

rmolinamir
  • 1,121
  • 14
  • 15