Toggle between class names on different scroll positions - When the user scrolls down 50 pixels from the top of the page, the class name "test" will be added to an element (and removed when scrolled up again). - Javascript DOM Event

Javascript examples for DOM Event:onscroll

Description

Toggle between class names on different scroll positions - When the user scrolls down 50 pixels from the top of the page, the class name "test" will be added to an element (and removed when scrolled up again).

Demo Code

ResultView the demo in separate window

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

<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