Reena Verma
Reena Verma

Reputation: 1685

Check browser width and fire event only once

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);
};

Upvotes: 0

Views: 88

Answers (1)

Lucas Bodin
Lucas Bodin

Reputation: 336

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);
    }
};

Upvotes: 1

Related Questions