简体   繁体   中英

How do I trigger jQuery when an anchor reaches the top of the viewport?

I need to trigger a jQuery function on a div when an anchor reaches the top of the viewport. There are a lot of posts on StackOverflow based on an element entering the viewport (ie the bottom of the viewport) see here for example.

Is it possible to trigger jQuery for the .nav-down element when the anchor #trigger hits the top of the view port?

HTML:

<div class="spacer"></div>
<a href="#" id="trigger">ANCHOR</a>
<div class="nav-down"></div>
<div class="spacer"></div>

jS:

function scroll_style() {
   var window_top = $(window).scrollTop();
   var div_top = $('#trigger').offset().top;

   if (window_top > div_top){
      $('.nav-down').css("background","green");
   }
}

$(function() {
  $(window).scroll(scroll_style);
  scroll_style();
 });

This jS/jSFiddle doesn't work as intended, but it'll give an idea of the thought process I have:

https://jsfiddle.net/vanstone/s643m85b/14/

Can anyone assist me with getting this to work?

You can try using the getBoundingClientRect() to get the position of <a> with respect to the viewport and then implement your logic.

In the below example, I am checking for top < 10 to factor in the height of <a>

 function scroll_style() { if ($('#trigger')[0].getBoundingClientRect().top < 10) { $('.nav-down').css("background", "green"); } else { $('.nav-down').css("background", "yellow"); } } $(function() { $(window).scroll(scroll_style); scroll_style(); }); 
 .spacer { height: 700px; background: red; } .nav-down { height: 250px; width: 100%; background: blue; } 
 <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script> <div class="spacer"></div> <a href="#" id="trigger">ANCHOR</a> <div class="nav-down"></div> <div class="spacer"></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM