0

I am trying to use a material-design-lite mdl-textfield inside of a mdl-menu.

The problem is, when I open the menu and click the textfield (<input>) it closes the menu.

Does anyone know how I can prevent this without recreating/styling the menu manually?

Here is example code:

#button {
  margin-left:20px;
  margin-top:20px;
}
<script src="https://code.getmdl.io/1.2.1/material.min.js"></script>
<link href="https://code.getmdl.io/1.2.1/material.indigo-pink.min.css" rel="stylesheet"/>


<button class="mdl-button mdl-js-button mdl-color--blue mdl-color-text--white" id="button">
  Open Menu
</button>
<ul for="button" class="mdl-menu mdl-js-menu">
  <li>
    <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
        <input class="mdl-textfield__input" type="text" id="sample3">
        <label class="mdl-textfield__label" for="sample3">Clicking here will close me :(</label>
    </div>
  </li>
  <li>item</li> 
  <li>item</li> 
  <li>item</li>
</ul>

Update

Solved this with a quick angular directive:

.directive('stopPropagation', function() {
    return {
        restrict: 'A',
        link: function($scope, $element) {
            $element.on('click', function($event) {
                $event.stopPropagation();
            });
        }
    };
});
d-_-b
  • 21,536
  • 40
  • 150
  • 256

1 Answers1

2

Try adding an event handler for the input field, where it prevents the event propagation

document.querySelector('.mdl-textfield__input').addEventListener('click', function(e) {e.stopPropagation()});

See snippet below.

#button {
  margin-left:20px;
  margin-top:20px;
}
<script src="https://code.getmdl.io/1.2.1/material.min.js"></script>
<link href="https://code.getmdl.io/1.2.1/material.indigo-pink.min.css" rel="stylesheet"/>



<button class="mdl-button mdl-js-button mdl-color--blue mdl-color-text--white" id="button">
  Open Menu
</button>
<ul for="button" class="mdl-menu mdl-js-menu">
  <li>
    <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
        <input class="mdl-textfield__input" type="text" id="sample3">
        <label class="mdl-textfield__label" for="sample3">Clicking here will close me :(</label>
    </div>
  </li>
  <li>item</li> 
  <li>item</li> 
  <li>item</li>
</ul>
<script>document.querySelector('.mdl-textfield__input').addEventListener('click', function(e) {e.stopPropagation()});</script>
Dimitris Karagiannis
  • 8,942
  • 8
  • 38
  • 63