views:

714

answers:

3

I am trying to make a div, that when you click it turns into an input box, and focuses it. I am using prototype to achieve this. This works in both Chrome and Firefox, but not in IE. IE refuses to focus the newly added input field, even if I set a 1 second timeout.

Basically the code works like this:

var viewElement = new Element("div").update("text");
var editElement = new Element("input", {"type":"text"});
root.update(viewElement);

// pseudo shortcut for the sake of information:
viewElementOnClick = function(event) {
    root.update(editElement);
    editElement.focus();
}

The above example is a shortened version of the actual code, the actual code works fine except the focus bit in IE.

Are there limitations on the focus function in IE? Do I need to place the input in a form?

A: 

What version IE? What's your DocType set to? is it strict, standards or quirks mode? Any javascript errors appearing (check the status bar bottom left for a little yellow warning sign) ? Enable error announcing for all errors via Tools > Options > Advanced.

Oisin

x0n
IE 7.0.5730.13 - I get no errors. using editElement.select() seems to focus the box, but it doesn't show the edit caret.
Staale
+2  A: 

My guess is that IE hasn't updated the DOM yet when you make the call to focus(). Sometimes browsers will wait until a script has finished executing before updating the DOM.

I would try doing the update, then doing

setTimeout("setFocus", 0);

function setFocus()
{
    editElement.focus();
}

Your other option would be to have both items present in the DOM at all times and just swap the style.display on them depending on what you need hidden/shown at a given time.

17 of 26
I thought I had already tried this, but your answer seems correct. I need to wait 500ms though for it to actually work. I think I will just go with always have and input element rather than a div.
Staale
A: 

The question is already answered by 17 of 26. I just want to point out, that Prototype has native mechanism for this: Function.defer()

Fczbkk