0

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?

Jeroen
  • 53,290
  • 30
  • 172
  • 279
panthro
  • 19,109
  • 50
  • 152
  • 271

2 Answers2

3

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>
0

Something like this (done with jQuery):

<div>Test</div>

$('div').hover(function() {
    $('body').attr('position','fixed');
    $('body').attr('overflow','hidden');
});
JonSnow
  • 466
  • 8
  • 36
  • not for the ones that use jQuery in nearly each and every project ;-) – JonSnow May 06 '15 at 15:03
  • @humble.rumble.6x3 Agreed. Unless OP is already using jQuery, Javascript is enough for this. – Praxis Ashelin May 06 '15 at 15:03
  • @SchweizerSchoggi Using jQuery for each and every project is a bad habit (which I admit being guilty of myself). jQuery is a very powerful plugin, but this also means that it adds a lot of extra load to your website. For small things, jQuery often is just overkill and Javascript would be a lot better performance-wise. That said, your answer is not bad. It can definitely be useful for future visitors which *are* using jQuery anyway. I'd just want to avoid recommending jQuery for everything to newbies. – Praxis Ashelin May 06 '15 at 15:11
  • believe me: we are not building kiddy apps.... we are building european web pages and it's helpful and needful to use jQuery in most of the projects. This is why I said: we use it nearly each and every time – JonSnow May 06 '15 at 15:17
  • @humble.rumble: he also did say nothing about using Javascript... so this is a stupid comment – JonSnow May 06 '15 at 15:19