Search code examples
javascriptfunctionbrowserresizewindow-resize

Check browser width and fire event only once


  • I want to check my browser/window width, for when it is below 669px.
  • When it is below 669px, I want to fire a function only once.
  • However, every time I resize my browser than further less than 669px, why function keeps on firing, with every resize.

How do I only fire an event once, once the user hits below 669px?

Here's the code I'm working with:

const checkWindowWdith = () => {
    console.log(document.documentElement.clientWidth);
    if (document.documentElement.clientWidth < 669) {
        //DO SOMETHING HERE
    };
};


//HERE I AM WAIT FOR THE USER TO FINISH RESIZING
var doit;
window.onresize = function(){
    clearTimeout(doit);
    doit = setTimeout(checkWindowWdith, 100);
};

Solution

  • I think you need to create a var who is set to false if the event was start and set to true if he never been start like this:

    var firstStartEvent = true
    
    const checkWindowWdith = () => {
        console.log(document.documentElement.clientWidth);
        if (document.documentElement.clientWidth < 669) {
            firstStartEvent = false;
            //DO SOMETHING HERE
        };
    };
    
    
    //HERE I AM WAIT FOR THE USER TO FINISH RESIZING
    var doit;
    window.onresize = function(){
        clearTimeout(doit);
        if (firstStartEvent) {
          doit = setTimeout(checkWindowWdith, 100);
        }
    };