zelda
zelda

Reputation: 753

How to immediately focus an element when it is added to the DOM

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.

Upvotes: 0

Views: 738

Answers (2)

marmeladze
marmeladze

Reputation: 6564

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>

Upvotes: 1

5eeker
5eeker

Reputation: 1027

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();
};

Upvotes: 1

Related Questions