0

I have a dropdown list which shows up on a button click. This dropdown list is not available in the DOM until the button is clicked. How can I get the focus on the first list item of this dropdown list as soon as it is added to the DOM.

Thank you.

zelda
  • 753
  • 2
  • 8
  • 19
  • [`element.focus()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus)? – qxz Feb 03 '17 at 05:38
  • The dropdown is being added at the end of the DOM and is absolutely positioned under the button which is being clicked. – zelda Feb 03 '17 at 05:41
  • @qxz element.focus() isn't working :( – zelda Feb 03 '17 at 05:41
  • Do you have a reference to the element that you want to focus? (Can you show us the code you're working with? Read [How to ask](http://stackoverflow.com/help/how-to-ask).) – qxz Feb 03 '17 at 05:41
  • Yes. I do have the reference. – zelda Feb 03 '17 at 05:43
  • you have angular considering you are using ng-if use the init event and pass the element to call the focus – Vinod Louis Feb 03 '17 at 05:43
  • Can you show us the code you're working with? Please [edit your question](http://stackoverflow.com/posts/42017455/edit). – qxz Feb 03 '17 at 05:44
  • You can apply a directive like http://stackoverflow.com/questions/40886012/how-to-navigate-focus-to-the-next-item-in-angular2/40886144#40886144 calls `elementRef.nativeElement.focus()` in `ngAfterContentInit()`. For each created element this directive will be instantiated and then `focus()` being called. – Günter Zöchbauer Feb 03 '17 at 06:45
  • 1
    @GünterZöchbauer That really helped. – zelda Feb 06 '17 at 19:11

2 Answers2

1

For ex: If your dropdown element id is "selectstate", then you could do it using getElementById

   <select id="state" name="state">
<option value="AB">AB</option>
<option value="AC">AC</option>
</select>


window.onload = function() {

    document.getElementById("state").focus();
};
5eeker
  • 1,016
  • 1
  • 9
  • 30
0

Below snippet will help you to create a dropdown button on DOM then focus it. Of course you've to improve it.

createDropdown = function(optsArray) {
  let dd = document.createElement("select");
  dd.setAttribute("id", "foo");
  for(var i =0; i<optsArray.length; i++) {
    let opt = document.createElement("option");
    opt.setAttribute("value", i);
    let optText = document.createTextNode(optsArray[i]);
    opt.appendChild(optText);
    dd.appendChild(opt);
}
  let cnt = document.getElementById("dropdown-container");
  cnt.innerHTML="";
  cnt.appendChild(dd);
  dd.focus();
} 

document.querySelector("button").addEventListener("click", function() {
  let opts = ["Marx", "Engels", "Lenin", "Gramsci", "Althusser", "Zizek"];
  createDropdown(opts);
})
#dropdown-container{
margin-top: 700px;
}
<button>Click me to load dropdown and focus it</button>

<div id="dropdown-container"></div>
marmeladze
  • 6,468
  • 3
  • 24
  • 45