Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot give .focus() to an element of a dropdown menu

Here is a Boostrap navigation bar, containing a dropdown menu, containing itself an <input>.

enter image description here

When I click on the dropdown menu, it is succesfully displayed. The value of the <input> is successfully changed to Bonjour but this <input> doesn't get the focus. Why ?

http://jsfiddle.net/rzsmdg4f/1/

How to give the focus to a input contained in a dropdown menu with .focus() ?


Code :

<div class="navbar navbar-default navbar-static-top" role="navigation">
    <div class="container">
        <ul class="nav navbar-nav">
            <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" id="maa">Dropdown<span class="caret"></span></a>
                <ul class="dropdown-menu" role="menu" style="min-width: 250px;">
                    <li>
                        <div style="padding:4px 20px;">Link:</div>
                    </li>
                    <li>
                        <div style="padding:4px 20px;">
                            <input class="form-control" id="ha" type="text" placeholder="blabla" />
                        </div>
                    </li>
                </ul>
            </li>
        </ul>
    </div>
</div>

JS :

{
    var maa = document.getElementById('maa');
    console.log(maa);
    maa.addEventListener('click', function () {
        console.log($('#ha'));
        $('#ha').val('Bonjour');
        $('#ha').focus();
    });
};
like image 306
Basj Avatar asked Sep 30 '14 21:09

Basj


People also ask

How do you focus in dropdown?

For the dropdown, we add a transform to make it animate from the corner. Then we add an opacity of 0 to hide it. Now we need to target the hover. We use the #user-menu:focus and then target the following (~) dropdown.

How to specify that the drop down list should automatically get focus when the page loads?

The <select> autofocus attribute is a boolean attribute that specifies that the drop-down list should automatically get focus when the page loads.


1 Answers

jsFiddle Demo

The element exists at the time of the click, so changing its value and logging it will properly show the current state of the element. However, it has not been displayed yet and as a result focusing it will not really have any effect. You could probably refactor some small snippet in the library to expose a hook that you could use to make your focus work. Or, you could make the observation that in the very next event handler the element will be visible and use a small timeout.

maa.addEventListener('click', function () {
    console.log($('#ha'));
    $('#ha').val('Bonjour');
    setTimeout(function(){$('#ha').focus();},10);//timeout here
});
like image 122
Travis J Avatar answered Sep 27 '22 21:09

Travis J