Search code examples
javascriptcustom-element

attributeChangedCallback not firing


problem is as follows, when I update the attr sticky either in the devtool or with js code I can't get the attributeChangedCallback to fire. The _updateSticky() method runs just fine when scrolling around, with adding and removing the sticky attr.

class HeaderLogo extends HTMLElement {

static get observedAttribute() {
    return ['alt-logo', 'sticky'];
}

constructor() {
    super();    
}

connectedCallback() {
   this._updateSticky();

    window.addEventListener('scroll', () => {
        this._updateSticky();
    }, false);
}  

attributeChangedCallback(attrName, oldVal, newVal) {    
    console.log("attr changed");    
}

/* evaluates if the logo should be in sticky state or not */
_updateSticky() {
    let scrollTop = window.pageYOffset || (document.documentElement || document.body.parentNode || document.body).scrollTop;
    let breakpoint = 50;

    if (scrollTop > breakpoint) {
        this.setAttribute('sticky', '');
    } else {
        this.removeAttribute('sticky');
    }
 }
}

window.customElements.define('header-logo', HeaderLogo);

Solution

  • It's just that you have a typo: observedAttribute should be observedAttributes.