Gyancode

A free library of HTML, CSS, JS

Search This Blog

Friday 24 June 2016

Add Class When Page Scroll Reach At Specific ID

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script type="text/javascript">
$(window).scroll(function (event) {
    var scroll = $(window).scrollTop();
    $('#home').toggleClass('about',
     //add 'ok' class when div position match or exceeds else remove the 'ok' class.
      scroll >= $('#about').offset().top
    );
    $('#home').toggleClass('product',
     //add 'ok' class when div position match or exceeds else remove the 'ok' class.
      scroll >= $('#product').offset().top
    );
    $('#home').toggleClass('contact',
     //add 'ok' class when div position match or exceeds else remove the 'ok' class.
      scroll >= $('#contact').offset().top
    );
});
//trigger the scroll
$(window).scroll();//ensure if you're in current position when page is refreshed

</script>
<style>
body{ margin:0px;}
#home{ height:500px; background:#3f9fc9;}
#about{ height:500px; background:#009294;}
#product{ height:500px; background:#ffde00;}
#contact{ height:500px; background:#b619ff;}
</style>
<body>
<header id="home">
</header>
<section id="about">
</section>
<section id="product">
</section>
<section id="contact">
</section>

</body>
</html>

No comments :

Post a Comment