Prevent Jquery Mobile popups from auto-closing in iOS

If you need to automatically/programmatically open a popup on iOS/Safari using Jquery Mobile, you will likely see your popup flash by very quickly and then close on its own. This is a huge annoyance, as there are times when an automatic popup is required, such as for on-load disclaimers, or confirmations.

The solution to this problem is out there, but hard to find: create a ‘safe’ popup open function that works in all browsers. The code for this (not mine, all credit is due to ArtenGr) can be found here. For findability, here’s a copy of the code:

/** Workaround for the jQuery Mobile popup opening bug.
 * @param {string} id The DOM id of the popup div. */
function popupSturdyOpen (id) {
  var ticksSeen = -1
  var interval = setInterval (function(){
    var hidden = $('#' + id + '-popup') .hasClass ('ui-popup-hidden')
    if (hidden || ++ticksSeen <= 0) {
      $('#' + id) .popup ('open')
    } else {
      if (++ticksSeen > 20) clearInterval (interval)
    }
  }, 100)
}

$("#indexpage") .on ("pagecreate", function () {
  popupSturdyOpen ('appPopup')
});

This will automatically open the following popup in all major browsers:

<div data-role="page" id="indexpage">
  <div data-role="popup" data-history="false" id="appPopup">test popup</div>
</div>

There’s also a more recent version of the code by the same author, but in my tests, it causes the popup to briefly close and then reopen in iOS.

Leave a Reply

Your email address will not be published. Required fields are marked *