Element className Property - Toggle between class names on different scroll positions - Javascript DOM

Javascript examples for DOM:Element className

Description

Element className Property - Toggle between class names on different scroll positions

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<head>
<style>
.test {//from   ww  w  .ja va 2 s. c o m
    background-color: yellow;
}
</style>
</head>
<body style="height:1500px">

<p>Scroll down this page</p>

<p id="myP" style="position:fixed">
This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. 
</p>

<script>
window.onscroll = function() {myFunction()};

function myFunction() {
    if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
        document.getElementById("myP").className = "test";
    } else {
        document.getElementById("myP").className = "";
    }
}
</script>

</body>
</html>

Related Tutorials