Posts Tagged ‘ie6’

IE6 Javascript Textbox Focus under Rails

Thursday, January 28th, 2010

Something unusual. While using Rails, I noticed one of my simple Javascripts wasn’t working under (surprise!) Internet Explorer 6. Usually, you can just grab the control by its ID using the DOM and then call the focus method:

document.getElementById("myControl").focus();

So, this wasn’t working. After some Googling, I found that there were some folks suggesting that the timing of the events was causing the focus() method to fire at the wrong time to work properly. The solution is to wait for the page to load completely before firing the Javascript code.

Under Prototype, this can be accomplished as such:

document.observe("dom:loaded", function()
{
$('myControl').focus()
});

or using JQuery, try the following:

jQuery(document).ready(function()
{
$("#myControl").focus()
});

I would be remiss if I did not mention the added benefit of unobtrusive code. By utilizing the observe(“dom:loaded” or (document).ready you can safely place all your Javascript into a separate linked file. Since the scripts will not fire until the page has completely loaded, there is never a need to embed the Javascript code directly into the webpage positioned after the controls you want to affect. Embedding Javascript is considered bad coding practice.


All works licensed under Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 Unported License. And that's a mouthful!