Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
163
rated 0 times [  166] [ 3]  / answers: 1 / hits: 18423  / 13 Years ago, sun, november 13, 2011, 12:00:00

I have an iframe (id: 'chat') with designMode='on' in Chrome.



On Enter keypress event I call the function send(), which takes the iframe contents and writes it to a socket. My problem is that when clearing the iframe, I lose focus.



How to do I set the focus so I can continue to type text in the iframe?



function send(){
var $iframe = $('#chat');
var text = $iframe.contents().text() + n;

socket.send(text);

// When this is done, the focus is lost
// If commented, the focus will not be lost
$iframe.contents().find('body').empty();

// My different failed attempts to regain the focus
//$iframe.focus();
//$iframe.contents().focus();
//$iframe.contents().find('body').focus();
//$iframe.contents().find('body').parent().focus();
//$iframe[0].contentWindow.focus();

// I've also tried all the above with timers
//setTimeout( function(){ $('#chat').contents().focus(); }, 100);
}


I've tried many of the solutions on other questions, but none seems to work.


More From » jquery

 Answers
52

The trick is to first set focus on the body and then create a Range.



var win = iframe.contentWindow;
var range = win.document.createRange();
range.setStart(win.document.body, 0);
range.setEnd(win.document.body, 0);
win.document.body.focus();
win.getSelection().addRange(range);

[#89150] Friday, November 11, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
manuel

Total Points: 747
Total Questions: 96
Total Answers: 95

Location: Argentina
Member since Thu, Mar 18, 2021
3 Years ago
;