简体   繁体   中英

How can I prevent onscroll function to trigger during resize?

I have two event handlers defined:

window.onresize = repositionElements;

scrollElement.onscroll = handleScrollBusiness;

Now, when I resize the window, I do not want my onscroll event to fire (which it ususally does during resizing). So I thought I temporarily set some isResizing variable to true and only set it back to false after a timeout. In the onscroll function I would then first of all check, if isResizing is false and only then proceed.

However, now during testing this, I realized that when I start to resize the window, it both fires a scroll and resize event, but it fires the onscroll event first , so my onresize has no chance to disable the scroll function, since it only gets fired after the scroll function has started to execute.

Is there any way around this? Can I globally change the order of these two events? If not, what other way would there to disable the onscroll event immediately once I start resizing?

I am looking for an answer in vanilla JavaScript. Also I am new to this, so if I have some logical flaws in my way to approach this, please let me know.

Thank you!

Since you haven't posted an example code of your problem, I'm not sure if what I'm about to write helps you or not.


You could try to defer the execution of onscroll handler by wrapping it's code inside a zero-length timeout, which effectively moves the execution of that piece of code to the end of current execution stack.

Here's an example:

window.onscroll = function () {
    setTimeout(function () {
        // your code here...
    }, 0);
}

window.onresize = function () {
    // your code here...
    // should be executed before onscroll handler
}

You can use RxJs Observable for this:

var resizeOb$ = Rx.Observable.fromEvent(window, 'resize');
var scrolOb$ = Rx.Observable.fromEvent(window, 'scroll')
              .takeUntil(resizeOb$);
scrolOb$.subscribe(function(event){

     /* handle scroll event here */
});
resizeOb$.subscribe(function(event){

     /* handle resize event here */
});

This will efficiently handle the situation for you.

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