Programmatically set focus of input box from ListView's ItemInvoked event [Windows 8 Metro HTML5]

JT703 picture JT703 · May 21, 2012 · Viewed 18.6k times · Source

Edit: If you have not developed on Windows 8, do not try to answer this question. Do not vote on it. Do not even read it. This is not a web app or website and does not run in a browser. Please stop down-voting content you do not understand. This is a Windows 8 METRO HTML5/js application that runs in the Windows Runtime environment.

Original Question:

I want the cursor to be "blinking" in the input box, ready to receive input. I'm using javascript to set the focus. This isn't working:

document.querySelector("#input-box").focus();

Anyone know why? Is the focus method not the correct one to use for this?

Thank you.

Edit #2: So it definitely has something to do with the fact that I am trying to set focus to the input from a ListView's "itemInvoked" event. The event is firing properly, the element is accessible from the event handler, and the line has no errors on execution. I can set focus to my input tag from a standard button click event, but not from an ItemInvoked event. So the question is, why can't I set focus from within this event handler?

Answer

ChristiaanV picture ChristiaanV · May 25, 2012

I have created this little test project with only a textbox and in the onload set the focus in exactly the same way as you do. I tried it both on the emulator and on my local machine and both methods seem to work.

Could you try if this project is working for you on your machine? And can you give us some more insight on when you are trying to set the focus? Right now in your question there is not that much information about when it's happening.

You can download the sample over here http://www.playingwith.net/Temp/TestFocusApplication.zip

Update

Okay, seem to found it, if you call the msSetImmediate function with the function that sets focus to the textbox it seems to work. I don't have an option to upload the test example, so below you find the code where I attach the ItemInvoked handler and call the setFocus function.

 var listView = document.getElementById("basicListView");

                listView.winControl.addEventListener("iteminvoked", function (evt) {
                    if (listView.winControl.selection.count() > 0) {                        
                        msSetImmediate(setFocus);
                    }
                });

function setFocus() {
            //Set focus on input textbox;
            var input = document.querySelector("#input-box")
            input.focus();
        }