How to trigger an on scroll event without scrolling

前端 未结 8 1209
梦毁少年i
梦毁少年i 2021-02-12 03:15

my Question is, how can i trigger (simulate or something esle) an on scroll event. In my special case I don\'t want to load all the Conservations in LinkedIn by scolling down al

相关标签:
8条回答
  • 2021-02-12 03:56

    As everybody replied, window.scrollTo(window.scrollX, window.scrollY); is work truly but in some cases, you should add a number to the windows current scroll position, for example in my case I added 1 to my scrollY and then called scrollTo method like this:

    window.scrollTo(window.scrollX, window.scrollY + 1);

    0 讨论(0)
  • 2021-02-12 03:57

    For my use-case I needed to change 'scrollX' to 'pageXOffset' and 'scrollY' to 'pageYOffset' to get a non-scrolling-scroll working in IE 11 (Internet Explorer):

        window.scrollTo(window.pageXOffset, window.pageYOffset - 1);
        window.scrollTo(window.pageXOffset, window.pageYOffset + 1);
    
    0 讨论(0)
  • 2021-02-12 04:02

    Sometimes you need find the scrollElement. In my case, my scrollElement is body and running on mobile, so below code works fine:

    document.body.scrollTo(window.scrollX, window.scrollY + 1);

    Hope it will be helpful.

    0 讨论(0)
  • 2021-02-12 04:03

    Alternatively, you can manually trigger a real scroll event as following:

    el.dispatchEvent(new CustomEvent('scroll'))
    

    Which feels a bit less of a hack (and more performant) than dual scrolling by +1 and -1 pixels...

    This should run any piece of code listening for a scroll event.

    Edit: To support IE11 or other legacy browser, consider using a CustomEvent polyfill such as mdn-polyfills

    0 讨论(0)
  • 2021-02-12 04:06

    You absolutely need a Javascript solution. What else is going to do the event listening/triggering, do you think?

    If you want to fire a scroll event, just literally scroll to where you already are by typing window.scrollTo(window.scrollX, window.scrollY); in your scripts or dev tools console. Alternatively, you can fake one using a combination of CustomEvent and the dispatchEvent function.

    If you want to trigger something on a scroll event, listen for scrolls using window.addEventListener("scroll", function(evt) { ... }); and make the handling function do whatever it is you need to do.

    0 讨论(0)
  • 2021-02-12 04:09

    window.scrollTo(window.scrollX, window.scrollY); is not working for me in Firefox. Nothing happens, and it seems to be because no scrolling actually needs to be performed to go to the place where you allready are.

    BUT window.scrollTo(window.scrollX, window.scrollY-1); is working. By this command the window.scroll event function is fired.

    (Trying to cheat by for instance: window.scrollTo(window.scrollX, window.scrollY-0) is not working either.)

    0 讨论(0)
提交回复
热议问题