0

I'm working with a div in an HTML page that I need to switch the css style of as I move the mouse throughout the page.

Is there any function I can use to constantly track the mouse location? I need to switch the particular div's css style to a different css style as soon as the mouse is at least 30 px from the top of the page. While the mouse cursor is within 30px distance from the top of the page, I want the div to have a particular style. If it is farther than 30 px from the top of the page, I want it to switch styles.

assume i have 2 different styles in my css I can switch back and forth.

coolmango
  • 11
  • 2
  • `document.body.addEventListener("mousemove", function(ev) { ... })` – Andreas Feb 27 '19 at 06:58
  • You should have a look to this answer: https://stackoverflow.com/questions/7790725/javascript-track-mouse-position/7790764#7790764 Have fun – Rurouni Feb 27 '19 at 07:05

2 Answers2

0

Use a mousemove event listener, and switch your styles by editing the href of a link attribute:

document.body.addEventListener("mousemove" event => {
    if (event.clientY >= 30) {
        document.querySelector("link").setAttribute("href", "style1.css");
    } else {
        document.querySelector("link").setAttribute("href", "style2.css");
    }
});
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
0

You can attach "mousemove" event and use 'event.clientY' to get current mouse top postion and write your requirements accordingly.

Here is an example below:

(function(){
        document.body.addEventListener("mousemove", function() {
            if (event.clientY >= 30) {
                document.querySelector(".myDiv").classList.remove('class2');
                document.querySelector(".myDiv").classList.add('class1');
            } else {
                document.querySelector(".myDiv").classList.remove('class1');
                document.querySelector(".myDiv").classList.add('class2');
            }
        });
    })();
 .myDiv {
        height: 200px;
        width: 200px;
        border:1px solid #f00;
    }
    .class1 {
        border-radius: 50%;
    }
    .class2 {
        border-radius: 10%;
    }
<!DOCTYPE html>
<head>
</head>
<body>
    <div class="myDiv"></div>
</body>
</html>
Md Junaid Alam
  • 1,131
  • 13
  • 20