4

It seems that i cannot call focus() on a textarea of my chrome extensions popup when it gets opened / after ondomready.

i have something like that in popup.js :

$(document).ready(function () {
   console.log($("#moped-text"));
   $('textarea').focus();   
   $('.container').css("color", "red");
});

i reference it in popup.html like that:

<html>
  <head>

    <link rel="stylesheet" href="css/content.css" type="text/css">

    <script type="text/javascript" src="js/lib/jquery.js"></script>
    <script type="text/javascript" src="js/popup.js"></script>
  </head>
 <body>
       <div class="container">
            <textarea name="newText"></textarea>
       </div>     
 </body>

The css-change works, the focus() does not!

When i debug the popup and type $('textarea').focus(); in the console, it works. Also events added inside the ready-callback are bound successfully.

Any help highly appreciated!

hc2p
  • 188
  • 1
  • 11
  • this isnt working for me neither: [Auto Focus in Google Chrome extension](http://stackoverflow.com/questions/6594064/auto-focus-in-google-chrome-extension) – hc2p Mar 10 '12 at 13:42

5 Answers5

4

i still don't know, why the focus is not set at the first place, but a simple timeout does the job :)

setTimeout(function() {
  $('#moped-text').focus();
}, 500);
hc2p
  • 188
  • 1
  • 11
  • 3
    This has always worked for me but in Chrome 18 (just made it to stable channel) this doesn't work. Even if I set the timeout to 1000 ms nothing happens. Do you experience the same thing, and if so do you perhaps know of a solution/workaround for the current situation? – pimvdb Mar 31 '12 at 20:45
3

Workaround for Chrome 18 (found here)

if(location.search !== "?foo")
{
  location.search = "?foo";
  throw new Error;  // load everything on the next page;
                    // stop execution on this page
}

Works for me!

IanW
  • 743
  • 5
  • 15
0

I use this to focus.

My element has "autofocus" as an attribute. When the form is loaded, the element with the attribute "autofocus" gets the focus.

.directive('autofocus', ['$timeout', function($timeout) { return { restrict: 'A', link : function($scope, $element) { $timeout(function() { $element[0].focus(); }); } } }])

David Ringsmuth
  • 325
  • 1
  • 12
0

You have div with class "container" not id. So use this instead:

$('.container').css("color", "red");
hamczu
  • 1,774
  • 12
  • 14
  • thanks hamczu! i changed my question accordingly. The css is not the problem, its the focus(). – hc2p Mar 10 '12 at 14:32
-1

You can simply use <textarea name="newText" autofocus></textarea>.

abraham
  • 46,583
  • 10
  • 100
  • 152
  • 1
    this does not work either. seems to be blocked in chrome extensions.. :( or something else is getting the focus afterwards – hc2p Mar 10 '12 at 18:04