2

I'm trying to implement a jQuery UI Selectmenu while using FastClick. Tapping one of the entries of the selecmenu's dropdown list is not registering on touch, closing the list without actually selecting the tapped list item. To remedy this, I'm using bind() to add the class .needsclick to the jQuery UI elements when they are created (as recommended in this answer). This is supposed to ensure that FastClick is not applied to the problematic elements.

Unfortunately, the class is only added once I've opened and closed the menu once, so it only works on the second attempt to select a list item, even though the elements are inserted the moment the page is loaded. How can I ensure it's added the moment the element is inserted by jQuery UI?

Here's a working CodePen that demonstrates the issue: http://codepen.io/dahdah/pen/qbePZK

JavaScript:

$(document).ready(function() {

  /* global FastClick */
  $(function() {
    FastClick.attach(document.body);
  });

  $('#filetype').selectmenu({
    width: '100%'
  });

  // Fix for FastClick breaking jQuery UI on mobile
  $('body').bind('DOMNodeInserted', function() {
    $(this).find('.ui-menu-item').addClass('needsclick');
  });

});

HTML:

<select id="filetype">
  <option selected=**strong text**"">Filetype</option>
  <option value="doc">DOC</option>
  <option value="pdf">PDF</option>
  <option value="html">HTML</option>
</select>
Community
  • 1
  • 1
Jerome Dahdah
  • 273
  • 2
  • 14

1 Answers1

2

So after some more research, it turns out that "jQuery does not get involved with node insertion events". A suggestion would be to try DOM MutationOberserver, but that's opening a whole can of worms for something that should be quick and simple.

I've solved my problem by listening for clicks on the element that jQuery UI creates to replace native elements like <select> and then adding .needsclick to the inserted list items:

$('.ui-widget').on('click', function(e) {
  $('.ui-menu-item').addClass('needsclick');
});

It needs to be done this way because the list items are only created after .ui-widget has been clicked.

Jerome Dahdah
  • 273
  • 2
  • 14