Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect a change event on an iOS7 select menu, before the user closes the popup?

On iOS 7, <select> menus in Mobile Safari do not fire a change event until after the user clicks "Done". Are there any other events I can listen for to know when the user's selection has changed?

<select onchange="alert('This will not fire until the user clicks Done')">
    <option>1</option>
    <option>2</option>
</select>
like image 615
Luke Dennis Avatar asked May 28 '14 03:05

Luke Dennis


1 Answers

There is no way to determine the new selection value before the user touches "Done".

When the user first touches the <select> control, iOS opens a native UI for the select options. This is not DOM. And when the user touches "Done" it sends the new value/index and fires the corresponding event back on DOM.

You can test this. Just setup two events: onfocus will setup a timer and continuously poll for selectedIndex until onblur destroys the timer when "Done" is touched.

<select id="my-select" onfocus="checkSelectedIndex()" onblur="selectDone()">
    <option>1</option>
    <option>2</option>
</select>
var timer;
// timer setup on focus
function checkSelectedIndex() {
    timer = window.setInterval(function () {
        console.log('selected index:', document.getElementById('my-select').selectedIndex);
    }, 500); // 2 polls per second
}

// timer cleared on blur
function selectDone() {
    console.log('Selection changed!');
    if (!timer) { return; }
    window.clearInterval(timer);
}

With this test, you'll see that even though you change the selected item on the UI; the logged index will not change until after you touch "Done" (which is when the final message is sent to DOM).

So, what you can do is; (with some UX trade off); instead of a <select> element, create a custom control which pops up a list of options in a <div> or <ul>. This way, you'll NOT be triggering the native UI and the user will not leave the DOM. And you'll be able to listen to the events of the menu and clicked items.

Just make sure your control feels mobile-friendly.

Enabling Safari Web Inspector for iOS Devices:

  1. On iOS device, go to: Setings » Safari » Advanced and enable Web Inspector.
  2. On desktop Safari, go to: Preferences » Advanced and check "Show Developer menu in menu bar". A new menu item named "Develop" will be added to you Safari menu.
  3. Connect your iOS device to your computer via USB.
  4. Open the page you want to debug (an external or localhost URL).
  5. From the desktop Safari Develop menu, select the name of your device and then click the application name in the submenu.
like image 130
Onur Yıldırım Avatar answered Oct 21 '22 19:10

Onur Yıldırım