Trigger event when user scroll to specific element - with jQuery

后端 未结 12 1500
攒了一身酷
攒了一身酷 2020-11-22 11:52

I have an h1 that is far down a page..

TRIGGER EVENT WHEN SCROLLED TO.

and I want to trigger an alert

12条回答
  •  鱼传尺愫
    2020-11-22 12:44

    Combining this question with the best answer from jQuery trigger action when a user scrolls past a certain part of the page

    var element_position = $('#scroll-to').offset().top;
    
    $(window).on('scroll', function() {
        var y_scroll_pos = window.pageYOffset;
        var scroll_pos_test = element_position;
    
        if(y_scroll_pos > scroll_pos_test) {
            //do stuff
        }
    });
    

    UPDATE

    I've improved the code so that it will trigger when the element is half way up the screen rather than at the very top. It will also trigger the code if the user hits the bottom of the screen and the function hasn't fired yet.

    var element_position = $('#scroll-to').offset().top;
    var screen_height = $(window).height();
    var activation_offset = 0.5;//determines how far up the the page the element needs to be before triggering the function
    var activation_point = element_position - (screen_height * activation_offset);
    var max_scroll_height = $('body').height() - screen_height - 5;//-5 for a little bit of buffer
    
    //Does something when user scrolls to it OR
    //Does it when user has reached the bottom of the page and hasn't triggered the function yet
    $(window).on('scroll', function() {
        var y_scroll_pos = window.pageYOffset;
    
        var element_in_view = y_scroll_pos > activation_point;
        var has_reached_bottom_of_page = max_scroll_height <= y_scroll_pos && !element_in_view;
    
        if(element_in_view || has_reached_bottom_of_page) {
            //Do something
        }
    });
    

提交回复
热议问题