Set focus to an element in an iframe

Posted in: Development

If you’re trying to set focus to an element in an iframe that has already been loaded, you need to set focus to the iframe first, then to the element.

Here is sample code:

if (ie) {
var myIframe = document.frames['my_iframe'];
var myField = document.frames['my_iframe'].document.getElementById('my_field');
}
else {
var myIframe = document.getElementById('my_iframe');
var myField = document.getElementById('my_iframe').contentDocument.getElementById('my_field');
}
if (!safari) {
myIframe.focus();
}
myField.focus();

In my use case, Safari didn’t take the iframe focus properly, but I didn’t take the time to test a generic case. If someone has time or interest in testing, please add a comment with your findings.

Hopefully this prevents someone from wasting as much time on this as I did.

Popularity: 2% [?]

Posted January 17th, 2006 @ 7:15 PM

3 Replies

  1. Matt adds this Comment:

    How would I go about doing the opposite of that – selecting an element in the page that the iframe is embedded in from the iframe?

    Is that even possible?

    January 18th, 2006 at 6:46 pm

  2. Alex adds this Comment:

    “top.” will always give you the topmost window. You can also use “parent.” and perhaps “opener.” (not sure how it works with iframes).

    January 18th, 2006 at 9:49 pm

  3. Hans adds this Comment:

    opener will do fine with iframe.
    opener will point to the opening window. From there you should be able to descend to it’s document.

    April 10th, 2006 at 1:07 am

Add a Comment

Please note: Use of a non-personal web site or blog URL in the field below and/or comments that are off-topic, personal attacks, or support requests will likely be removed at my discretion. If you need help with WordPress or a WordPress plugin, please contact the WordPress HelpCenter.

Note: This post is over 4 years old. You may want to check later in this blog to see if there is new information relevant to your comment.

» «

About This Site

This is the personal web site of Alex King, a web developer in Denver, Colorado USA. More...


Crowd Favorite

Crowd Favorite is my software and web development business.

We build web applications, design and develop custom WordPress themes and plugins, and build custom sites using WordPress as a CMS.


I also have a tumblog that aggregates my online content from other services (Twitter, Flickr, del.icio.us. etc.).

America - america09.com

Ads