I'm trying to find the focused item within an iframe but failing!
Whenever I insert into the iframe the item appears to be focused, for example if I insert a table then the cursor is always in the last cell.
As a I test I am trying to change the background color of the cell to see if it is working but this always changes the iframe body not the item inserted
var d1 = $.Deferred(); $.when(d1).then(function () { var $iframe = $("#ifr").contents(); var focused = $iframe.find(':focus'); focused.css("background", "red"); console.log(focused); }) d1.resolve(insertTable(html));
d1
is just a call of a function that uses the execCommand() to insert into the iframe.
Is it at all possible to find the focused element and store it in this method?
2 Answers
Answers 1
The body
element is the fallback if no other element has focus:
There may be no element focused; when no element is focused, key events received by the document must be targeted at the body element, if there is one, [...] User agents [...] may support only one focused element per top-level browsing context — user agents should follow platform conventions in this regard.
See also the CSS :focus
selector. Your problem is that only one element in the whole browsing context can have focus. If the focus is not within the iframe
, it is somewhere else, and the iframe
's body
element is that fallback.
https://www.w3.org/TR/html5/browsers.html#nested-browsing-context says that iframe
s are nested browsing contexts, not top-level browsing contexts. So is seems as though there's only one focused element for the whole page. If that is not within your iframe
, its body
is returned instead.
Answers 2
Put this script inside your iframe page.
$("body").delegate( "*", "focus blur", function() { var elem = $( this ); setTimeout(function() { elem.toggleClass( "focused", elem.is( ":focus" ) ); }, 0 ); });
Sample iframe page is -
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style> .focused {background: #F00;} </style> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> </head> <body> <form action="#"> First name:<br><input type="text" name="firstname" value="Mickey" > <br> Last name:<br><input type="text" name="lastname" value="Mouse"> <br><br><input type="submit" value="Submit"> </form> <script> $("body").delegate( "*", "focus blur", function() { var elem = $( this ); setTimeout(function() { elem.toggleClass( "focused", elem.is( ":focus" ) ); }, 0 ); }); </script> </body> </html>
0 comments:
Post a Comment