1

So, related to an earlier question, but forgive me for my naive javascript ways. Basically I now want to automatically bring a text input into focus when it is added to the DOM. Part of me thinks that I might be trying to add focus to the object before it exists, but I'm not quite sure how I would go about fixing it. Right now this is my relevant code:

var searchWrapper = document.createElement("div");
searchWrapper.id = "search-wrapper";

this.parentNode.replaceChild(searchWrapper, this);
document.getElementById("search-wrapper").focus();

But it's not quite working. Should I be setting focus as a callback on replaceChild, or is there some other way to do this?

Slater Victoroff
  • 21,376
  • 21
  • 85
  • 144

1 Answers1

1

Try the following:

Live Demo

var searchOrig = document.getElementById("search-wrapper"); 

var searchWrapper = document.createElement("div");
searchWrapper.id = "search-wrapper";
searchWrapper.setAttribute('tabindex', '0'); 

searchOrig.parentElement.replaceChild(searchWrapper, searchOrig);
document.getElementById("search-wrapper").focus();
Brandon Boone
  • 16,281
  • 4
  • 73
  • 100
  • Oh, awesome, even better! Out of curiosity, where does that focus border get defined? Is that something just automatically generated? – Slater Victoroff Jul 15 '13 at 15:27
  • It is part of the [outline](http://www.w3schools.com/css/css_outline.asp) property in css. You can set it via `div:focus { outline:2px solid blue !important; }` – Brandon Boone Jul 15 '13 at 15:31