0

This should be easy, but it's driving me crazy. I'm popping up a jQuery Tools overlay form that contains a textarea, and I want that textarea to have focus when it appears. The form itself is working fine, but I can't get the focus to stick. The following code runs when the form is presented:

$(document).ready(function () { 
     console.log('firing!');]
     $('#edit-comment').css('color', '#ff0000');
     $('#edit-comment').focus();
 });

When the form appears, I get the entry in console.log and I get the change in color of the textarea, so the code is definitely running and finding the textarea. But I DON'T get the focus set to the textarea.

I'm finding this very strange. Any insights out there?

Jim Miller
  • 3,291
  • 4
  • 39
  • 57

3 Answers3

1

I suspect that the code runs before the #edit-comment is created in the DOM. Your code runs on document.ready, it seems.

Try running the $('#edit-comment').focus(); code inside the function that loads the overlay, and see if that helps.

Arno
  • 1,253
  • 14
  • 21
0
$(function() {
   console.log("firing!");
   document.getElementById("edit-comment").style.color = "#F00";
   document.getElementByID("edit-comment").focus();
});

But color will change the text color. If you want to change the background, use .backgroundColor, if you want to change border, use .borderColor

André Silva
  • 1,149
  • 9
  • 30
  • The color change thing is just a test call I put in to make sure that I was finding the textarea properly and that I could do SOMETHING to it -- it won't be there for real. But anyway, (a) how is the document.getElementById call any different than the jQuery call and (b) I tried it, and it doesn't work either. ?? – Jim Miller Apr 20 '12 at 19:10
  • Weird, I have an webapp doing that and it's working, I just tested a quick html using that with Chrome and worked but with IE 8 didn't. That should actually work. – André Silva Apr 20 '12 at 19:25
  • Yeah, that's why it's so weird :). Re IE 8 -- check http://api.jquery.com/focus/ -- IE apparently breaks if the form element is not visible when the call is made. I tried modifying the code above to make the focus() call inside a show() handler hung off the textarea, but still no luck. – Jim Miller Apr 20 '12 at 19:40
0

Not answered so much as punting. Time's a'wasting; I found another way to do much the same thing. I think Arno's point about exactly when #edit-comment was created is a part of it; in any case, thanks for the help!

Jim Miller
  • 3,291
  • 4
  • 39
  • 57