0

I am working on an MDL site. There is known issue that they still don't give a default select form element. The solution I found was to use a menu component, which will show when the input is clicked. Works well. But I noticed that the menu will not show up when the input is focused using the TAB key. So I put this in jQuery:

/*
Make menus show up on input focus
*/
$('.mdl-textfield__input').focus(function(){
    $(this).click();
});

This works well for showing the menu on TAB driven focus. But the problem is that now when I click on the input, it will show and then hide the menu. The real click shows it and the next simulated click from my code will cause it to close.

I am wondering if I can tell if the focus state was driven by a click or not, and condition my jQuery code on that. So if the focus was driven from a click then I don't need to simulate the click?

Here is an example of the MDL HTML code:

<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label {% if form.errors.gender %}is-invalid{% endif %}">
    <label class="mdl-textfield__label" for="gender">Gender</label>
    <input class="mdl-textfield__input" id="id_gender" name="gender" type="text" readonly value="{{ form.gender.value }}" readonly>
    <ul class="mdl-menu mdl-menu--bottom-left mdl-js-menu mdl-js-ripple-effect select-menu" for="id_gender">
        <li class="mdl-menu__item" data-val="m">Male</li>
        <li class="mdl-menu__item" data-val="f">Female</li>
        <li class="mdl-menu__item" data-val="t">Transgender</li>
        <li class="mdl-menu__item" data-val="o">Other</li>
    </ul>
    <span class="mdl-textfield__error">{{ form.errors.gender.as_text }}</span>
</div>
jeffery_the_wind
  • 17,048
  • 34
  • 98
  • 160

2 Answers2

0
$('body').on('focus', '.mdl-textfield__input', function(e){
    $(this).trigger('click')
});
0

I had the exact same issue with a Drupal Superfish mobile menu and found the answer here Detect if focus event was triggered by user/browser or jQuery

That answer specifically works for clicks, but you can rework for either. Should be something like this:

var isUserClick = false;
$('.mdl-textfield__input').mousedown(function(){
   isUserClick = true;
});
$('.mdl-textfield__input').focus(function(e){
  if (isUserClick === false){
    $(this).click();
  } else {
    isUserClick = false;
  }
});
C0c0b33f
  • 176
  • 7