2

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

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
AnApprentice
  • 108,152
  • 195
  • 629
  • 1,012
  • With jQuery, you could do: `$("textarea").live("focus", function(e) {$(this).closest("comment-wrap").css({background: "red"})});` – Shaz Sep 23 '11 at 00:40
  • 1
    CSS alone won't do it (doesn't support parent selectors). You'll need a bit of javascript: http://stackoverflow.com/questions/2212583/affecting-parent-element-of-focusd-element-pure-csshtml-preferred – Pat Sep 23 '11 at 00:41
  • 1
    possible duplicate of [Complex CSS selector for parent of active child](http://stackoverflow.com/questions/45004/complex-css-selector-for-parent-of-active-child) – davin Sep 23 '11 at 00:42

3 Answers3

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

Styx
  • 9,863
  • 8
  • 43
  • 53
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.

Community
  • 1
  • 1
davin
  • 44,863
  • 9
  • 78
  • 78
0

With JavaScript and jQuery, you could do:

$("textarea").live("focus", function(e) {
    $(this).closest(".comment-wrap").css({
        "background": "red"
    });
});
Shaz
  • 15,637
  • 3
  • 41
  • 59
  • You're missing `.`, and misusing `live()`, and should probably reference `textarea` in some context. – davin Sep 23 '11 at 00: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 Sep 23 '11 at 00: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 Sep 23 '11 at 01:04