开发者

jQuery trigger action when a user scrolls past a certain part of the page

Hey all, I need a jQuery action to fire when a user scrolls past certain locations on the page. Is this even possible with jQuery? I have looked at .scroll in the jQuery API and I don't think this is what I need. It fires every time the user scrolls, but I need it to fire just when a user passes a certain area开发者_如何学编程.


Use the jquery event .scroll()

$(window).on('scroll', function() {
    var y_scroll_pos = window.pageYOffset;
    var scroll_pos_test = 150;             // set to whatever you want it to be

    if(y_scroll_pos > scroll_pos_test) {
        //do stuff
    }
});

http://jsfiddle.net/babumxx/hpXL4/


Waypoints in jQuery should do it: http://imakewebthings.github.com/jquery-waypoints/

$('#my-el').waypoint(function(direction) {
  console.log('Reached ' + this.element.id + ' from ' + direction + ' direction.');
});

jQuery waypoints plugin documentation: http://imakewebthings.com/waypoints/guides/jquery-zepto/


To fire any action only once on a single page I have modified jondavid's snippet as following.

jQuery(document).ready(function($){

    $triggered_times = 0;

    $(window).on('scroll', function() {

            var y_scroll_pos = window.pageYOffset;
            var scroll_pos_test = 150;   // set to whatever you want it to be

            if(y_scroll_pos > scroll_pos_test && $triggered_times == 0 ) {

                //do your stuff over here

                $triggered_times = 1;   // to make sure the above action triggers only once

            }
    });

})


Scroll down to Run code snippet

Here you can check example of working code snippet;

jQuery(document).ready(function($){

		$triggered_times = 0;

		$(window).on('scroll', function() {
				var y_scroll_pos = window.pageYOffset;
				var scroll_pos_test = 150;   // set to whatever you want it to be

				if(y_scroll_pos > scroll_pos_test && $triggered_times == 0 ) {
					alert('This alert is triggered after you have scroll down to 150px')
					$triggered_times = 1;   // to make sure the above action triggers only once
				}
		});

	})
p {
    height: 1000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<p>scroll down this block to get an alert</p>
</body>

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜