javascript - navigation bar 'highlight' function -


i've written jquery highlights 'about', 'my projects', or 'contact me' text on navigation bar when corresponding page section being viewed. in order i'm using scroll() event listener:

$(document).scroll(function myfuction() {     if ($(document).scrolltop() >= $("#contactme").offset().top) {         $("#contactbutton").addclass("active");         $("#projectbutton").removeclass("active");         $("#aboutbutton").removeclass("active");            } else if ( $(document).scrolltop() > $("#portfolio").offset().top && $(document).scrolltop() < $("#contactme").offset().top) {         $("#contactbutton").removeclass("active");         $("#projectbutton").addclass("active");         $("#aboutbutton").removeclass("active");     } else if ( $(document).scrolltop() > $("#about").offset().top && $(document).scrolltop() < $("#portfolio").offset().top)  {         $("#contactbutton").removeclass("active");         $("#projectbutton").removeclass("active");         $("#aboutbutton").addclass("active");     } }); 

when user scrolls, function checks see top of page scrolltop(), , adds or removes "active" class highlights appropriate text.

i understand though having action performed within event listener bad idea, i'm not sure how else go accomplishing i'm trying do. perhaps i'm somehow re-inventing wheel here?

i have imagined bootstrap library have had pre-packaged class this, no luck in finding that.

you class items, cache them jquery collection, , on scroll check if of them in viewport - based on can perform needed action.

fast demo:

var $items = $('.item')  var $window = $(window);  var $document = $(document);    function inviewport(el) {    var rect = el.getboundingclientrect();    return (      rect.bottom > 0 &&      rect.right > 0 &&      rect.left < $window.width() &&      rect.top < $window.height()    );  };    $document.on('scroll', function(){    $items.each(function(){      if(inviewport(this)) {        $items.removeclass('active');        $(this).addclass('active');        return false;      }    })  }).trigger('scroll');
.item {    width: 100%;    height: 150px;    margin-bottom: 50px;    background-color: #ddd;  }    .item.active {    background: red;  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <div class="item"><span>#1</span></div>  <div class="item"><span>#2</span></div>  <div class="item"><span>#3</span></div>  <div class="item"><span>#4</span></div>  <div class="item"><span>#5</span></div>  <div class="item"><span>#6</span></div>  <div class="item"><span>#7</span></div>  <div class="item"><span>#8</span></div>  <div class="item"><span>#9</span></div>  <div class="item"><span>#10</span></div>

it's idea throttle scroll calls https://lodash.com/docs/4.17.4#throttle or own implementation.


Comments