3

I have the following

<div class="comment-wrap">
 <textarea></textarea>
</div>

Whenever the textarea is in focus, I want to style the comment-wrap div. I've tried:

#hallPost-inner + textarea:focus {
    background: red;
}

This does not work. Any ideas on how I can style the comment-wrap div whenever the textarea is in focus, meaning the cursor is blinking in the textarea and the user can type?

Thanks

3

3 Answers 3

1

Not sure what #hallPost-inner is, but in general CSS selectors cannot ascend, meaning you would need to have the textarea:focus selector, but then would need to style an ancestor element, which cannot be done in css. Here's a good resource, among many others. The link shows how an easy javascript solution can be achieved as well.

1

Use the pseudo selector :focus-within. Note that any child in focus will effect the parent. If you have more children and just wanna apply when the event hits the <textarea>, you will need JS.

Link for more details. (css-tricks)

Ex.:

form{
  padding: 20px;
  background-color: gainsboro
}

input{
  text-align: center
}

form:focus-within {
  background-color: yellow
}
<form>
  <input type="text" placeholder="name">
  <input type="text" placeholder="lastname">
  <input type="button" value="Go!">
</form>

Note: not all browsers support :focus-within

0

With JavaScript and jQuery, you could do:

$("textarea").live("focus", function(e) {
    $(this).closest(".comment-wrap").css({
        "background": "red"
    });
});
3
  • You're missing ., and misusing live(), and should probably reference textarea in some context.
    – davin
    Commented Sep 23, 2011 at 0:46
  • @davin Thanks, class selector fixed. How is this misusing .live()? Using only .live() for event listeners only actually creates one universal event listener on the document or window.
    – Shaz
    Commented Sep 23, 2011 at 0:54
  • live has some disadvantages/limitations; it cannot properly prevent event propagation, it doesn't support all jquery chained traversals, and doing a regular bind would also only bind one universal event, even if it there were more references to it.
    – davin
    Commented Sep 23, 2011 at 1:04

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