0

For my Website, I have a set background-color of the body, for example

body {
background-color: #FFFFFF;
}

I also have a button defined in the .html-File (Let's say it has the ID "button1"), and I want the Background-Color of the body to change (to for example #000000;) when the button is beeing hovered over with a mouse and change back when the mouse isnt on the button anymore. Is there a way to do this?

I am a new webdeveloper and am still looking at/learning JavaScript.

iamflee_
  • 27
  • 1
  • 6
  • Also, see [Is there a CSS parent selector?](https://stackoverflow.com/questions/1014861/is-there-a-css-parent-selector) – Boaz Mar 22 '18 at 14:03

2 Answers2

1

It's not possbile in CSS. In JavaScript it's quite easy, you're looking for onmouseover/out events.

var button = document.getElementById('hover');
var body = document.body;

button.onmouseover = function() {
 body.className = 'hovered';
}

button.onmouseout = function() {
 body.className = '';
}
body {background: #000;}
body.hovered {background: #ff0;}
<button id="hover">button</button>
pavel
  • 26,538
  • 10
  • 45
  • 61
1

Using pure css, you can add a background div:

#button:hover ~ #background {
  background-color: red;
}

#background {
  position:absolute;
  background-color: blue;
  top: 0px;
  right: 0px;
  bottom: 0px;
  left: 0px;
  z-index: -1;
}
<button id="button">Button</button>
<div id="background"></div>
SystemGlitch
  • 2,150
  • 12
  • 27