I would like my logo to make one full rotation as you scroll to the bottom of the page. How?

207 views Asked by At

My current code makes my logo rotate on scroll, but it makes more than one full rotation. How do I make it rotate only once throughout the entire page scroll?

P.S. Obviously, page height will vary; 10000px is for demo purposes only. Also, I divided window.pageYOffset by 10 to slow down rotation speed a little.

var logo = document.getElementById("logo");
window.addEventListener("scroll", function() {
    logo.style.transform = "rotate("+window.pageYOffset/10+"deg)";
});
.main {
    height:10000px;
}

#logo {
    position:fixed;
}
<div class="main">
    <div id="logo">
        <img src="https://files.cargocollective.com/c100310/test.svg" alt>
    </div>
</div>

1

There are 1 answers

6
Jaromanda X On BEST ANSWER

Use 360 * window.pageYOffset / (document.documentElement.scrollHeight - document.documentElement.clientHeight) to calculate the angle

var logo = document.getElementById("logo");
window.addEventListener("scroll", function() {
    logo.style.transform = "rotate("+(360 * window.pageYOffset / (document.documentElement.scrollHeight - document.documentElement.clientHeight))+"deg)";
});
.main {
    height:10000px;
}

#logo {
    position:fixed;
    transition: transform 1s;
}
<div class="main">
    <div id="logo">
        <img src="https://files.cargocollective.com/c100310/test.svg" alt>
    </div>
</div>