0

so I am looking for a way to apply CSS style to an element when another is being hovered.

To illustrate better, then here's an example:

Html:

<body>
    <p>Click me</p>
</body>

Css:

p:hover{
    background-color: red;
}

So essentially I want the body to have the background color of red whenever the p is being hovered.

Tobias H.
  • 426
  • 1
  • 6
  • 18
  • 1
    CSS doesn't support that. The `:has` pseudo-class would do that: `body:has(p:hover) { background-color: red; }`. Sadly, it is not yet supported by any browser. – Guffa Oct 15 '21 at 18:03

2 Answers2

0

With a simple JavaScript, you can achieve this very easily.

const clickEl = document.getElementById("click-para");
clickEl.addEventListener("mouseenter", () => {document.body.style.backgroundColor = "red";})
clickEl.addEventListener("mouseleave", () => {document.body.style.backgroundColor = "white";})
<p id="click-para">Click Me</p>
Jade
  • 40
  • 7
  • The target to change the background is supposed to be the body of the page and not just the p tag. Just in case you want to try this, it would be necessary to modify the code. – cvillalobosm Oct 15 '21 at 18:19
  • Ah - thank you for catching my mistake! Updated my answer. – Jade Oct 15 '21 at 19:29
0

The fastest way I know to do this without any extra plugin is using jQuery.

Check the following example:

$("#action").mouseenter(function() {
  $('body').css('background-color', 'red');
});

$("#action").mouseleave(function() {
  $('body').css('background-color', 'white');
});
body{
  transition: background 0.7s ease;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
  <body>
      <p id='action'>Click me</p>
  </body>
<html>

I added an ID to the 'p' element to reference it from the JS code.

You will notice the transition in css is just to smooth the color change animation.

cvillalobosm
  • 156
  • 2
  • 12