JMK
JMK

Reputation: 28059

Change style of another element when contenteditable has focus

I want to change the style of another element when a contenteditable div has focus as shown below:

[contenteditable="true"]:focus .testClass {
    background-color: black;
}
<div contenteditable="true">Hello World</div>
<button class="testClass">Test</button>

Unfortunately the above isn't working, I have tried the following CSS also:

[contenteditable="true"]:focus + .testClass {
[contenteditable="true"]:focus > .testClass {
[contenteditable="true"]:focus, .testClass {

Using [contenteditable="true"]:focus on its own works fine to style the editable div when focus is applied, but none of these work to style another element at the same time. Is this possible to do?

Upvotes: 1

Views: 656

Answers (4)

Jeff Labour
Jeff Labour

Reputation: 41

[contenteditable="true"]:focus ~ .testClass will do the job as Fahad Hasan said

The ~ symbol means the first element right after ( not child )

Upvotes: 1

Syed Muhammad Zeeshan
Syed Muhammad Zeeshan

Reputation: 1045

you can change the style of .textClass when your div has focus, by using jquery:

$("div[contenteditable=true]").focusin(function () {

    $(".testClass").css({
        "background-color": "black",
    });

});

Upvotes: 0

Fahad Hasan
Fahad Hasan

Reputation: 10506

You need to use ~. It's the general sibling selector which separates two selectors and matches the second element only if it is preceded by the first, and both share a common parent. Check this:

[contenteditable="true"]:focus ~ .testClass {
     background: red;
}

[contenteditable="true"]:focus ~ .testClass {
  background: red;
}
<div contenteditable="true">Hello World</div>
<button class="testClass">Test</button>

More about the general sibling selector can be read over here.

Upvotes: 1

Alex Shesterov
Alex Shesterov

Reputation: 27525

Is this what you want:

[contenteditable="true"]:focus {
    background-color: black;
}
<div contenteditable="true">Hello World</div>
<button class="testClass">Test</button>

Or this (you mentioned you've tried it, but it does work):

[contenteditable="true"]:focus + .testClass {
    background-color: black;
}
<div contenteditable="true">Hello World</div>
<button class="testClass">Test</button>

Here some reading on CSS selectors: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_started/Selectors

Upvotes: 1

Related Questions