0

Is there an easy way to highlight a top with id (apply css-class with specific color f.e.) after user scrolls to it? I have a scrollspy on page, but it seems that plugin will not help me, so I can't make to ends meet.

P.S. I didn't find alike info in Google or StackOverflow, so please, don't get me wrong.

There is a rough example of page

https://jsfiddle.net/masyurik/kdnzdeb2/#&togetherjs=DeaMiBADpp

HTML

<div id="secA" class="section">
Hello it's secA
  <div>
      <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
  </div>
</div>

<div id="secB" class="section">
Hello it's secB
  <div>
      <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
  </div>
</div>

<div id="secC" class="section">
Hello it's secC
  <div>
      <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
  </div>
</div>

CSS

.section {
  background-color: red;
}

.active {
  background-color: yellow;
}
Aleks Maksiuta
  • 49
  • 1
  • 12

3 Answers3

0

You can use jquery-waypoints to know which element has reached at top of the viewport. The plugin will give you the callback which will help you to change the css of the active element.

Sandeep Sukhija
  • 1,156
  • 16
  • 30
0

You need to use scrollevent and change the class accordingly... kindly check https://jsfiddle.net/77v3329y/1/

jQuery

$(document).ready(function() {
  var a = +$('#secA').height();
  var b = $('#secB').height();
  var c = $('#secC').height();
  console.log(a);
  console.log(b);
  console.log(c);
  $(window).on('scroll', function() {
    $('#secA, #secB, #secC').removeClass('active');
    var st = $(document).scrollTop();
    if (st < a) {
      $('#secA').addClass('active');
    }
    if (st > a) {
      $('#secB').addClass('active');
    }
    if (st > a + b) {
      $('#secC').addClass('active');
    }
  })
});
RRR
  • 1,074
  • 8
  • 11
  • Oh, very good! But, if I have 20 id's, I just need to pass it like this $('#secA, #secB, ..., #secZ') or should I pass them like an array or smth alike? – Aleks Maksiuta Mar 22 '16 at 07:53
  • better to use nth-child thats helpful even when you dont know the number of divs on page... have same class names for all the divs so it helps to find out the length – RRR Mar 22 '16 at 08:08
0

Here is the solutions to detect the scroll to top event. Fire event when div is visible to visitor with jQuery?

Simply use jQuery to change the css of the element when scroll to top: $("#secA").css("background-color", "yellow");

Community
  • 1
  • 1
ThorChiam
  • 163
  • 1
  • 7