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?

3 Answers 3

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.

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

3
  • 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, 2012 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. Apr 20, 2012 at 19:25
  • Yeah, that's why it's so weird :). Re IE 8 -- check 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, 2012 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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.