1

I want to ad an eventListener for window resize inside my custom lightning web component but I don't know how to do it

Maybe something like this?

constructor(){
    window.addEventListener('resize', this.handleResize());
}
handleResize(){
    //custom code
}
3

you need to pass the function by reference and not invoke it directly while declaration. Later it will be invoked when the event is triggered. PFB:

connectedCallback() {
    window.addEventListener('resize', this.myFunction);
}
@track count = 0;
myFunction = () => {
    this.count = this.count += 1;
    console.log('resized => ', this.count);
};

Here is the playground link

| improve this answer | |
  • How long do you think the window support would be there for LWC? – Arthlete May 16 at 3:01
  • @Arthlete, I think it will be always supported. Salesforce documentation uses window here. Also locker apis shows it available. Also Lwc is meant to be close to normal web development as close as possible. If they limit so many things, lwc will follow aura (sometime extinct) – salesforce-sas May 16 at 6:15
0

If you want to access 'this' in the event handler, you need to:

window.addEventListener("resize", this.myFunction.bind(this))
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.