Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vanilla javascript function based on screen resize

I am trying to execute a function by resizing the window. The function is changing the color of the body based on screen resizing. If the screen size is less than 500px body should be in 'Red', else it should be 'Green'. I wrote a function, but it is not working in resizing. It works only after refreshing the browser. I want to execute the function without refresh. Following is the code. Thanks in advance for anyone's help.

HTML:

<div class="trigger">Trigger</div>
<div class="content">This is the Toggle Displaying content</div>

JavaScript:

doit=()=>{
if(window.innerWidth<500) {
document.body.style.background="red";
}
else {
document.body.style.background="green";
}
}
doit();
like image 349
Ren Jitsm Avatar asked Jan 21 '26 07:01

Ren Jitsm


1 Answers

Try the following:

doit = () => {
    const fn = () => {
        if(window.innerWidth<500) {
            document.body.style.background="red";
        }
        else {
            document.body.style.background="green";
        }
    }
    fn()
    window.addEventListener('resize', fn)
}
doit();
like image 140
Rateb Habbab Avatar answered Jan 22 '26 19:01

Rateb Habbab



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!