panthro
panthro

Reputation: 24059

Add styles to body when hovering a div on the page

I know I can prevent a page from scrolling using:

body {
    position: fixed;
    overflow: hidden;
}

But I need these styles to be applied when the user is hovering over a div on my page.

Is there a way to apply styles to the body like this - from inside a hover?

Upvotes: 0

Views: 81

Answers (2)

user4639281
user4639281

Reputation:

There is no way to style a parent with CSS, but you can use javascript. Note I've added a line for the background color to simulate the effect, this can be removed for your purposes.

document.getElementById("hover").onmouseover = function() {
  // on hover set the body to position fixed and overflow hidden
  document.body.style.position = "fixed";
  document.body.style.overflow = "hidden";
  document.body.style.background = "rgba(0,75,250,0.5)";
}
document.getElementById("hover").onmouseout = function() {
  // when the user is done hovering, reset
  document.body.style.position = "";
  document.body.style.overflow = "";
  document.body.style.background = "";
}
<div id="hover">Hover over me</div>

Upvotes: 3

JonSnow
JonSnow

Reputation: 335

Something like this (done with jQuery):

<div>Test</div>

$('div').hover(function() {
    $('body').attr('position','fixed');
    $('body').attr('overflow','hidden');
});

Upvotes: 0

Related Questions