Search code examples
javascriptweb-componentcustom-element

Click event added to a button that is in a web component works only once


I have a class that contains three buttons that are used to navigate the app back and forth and so the content gets changed. However, the eventlisteners that I attempt to add to these three buttons on connectedCallback method, doesn't fired after it works once. When I click one of the buttons, f.e. next button, it does what expected: changes attribute of the other element but when I try to click and want to see a new screen, it doesn't work anymore. In inspector, I also looked for the events attached to the buttons, they stay there while buttons aren't work.

Is there anything that I miss. It's probably because of the shadow DOM but I couldn't figure it out.

Thanks in advance!

export class NavigationButtons extends HTMLElement {

constructor() {
super();
this.attachShadow({ mode: "open" });
this.render();

if (this.shadowRoot) {
    const styleSheet = document.createElement("style");

    styleSheet.textContent = styles;

    this.shadowRoot.append(
      navigationButtons.content.cloneNode(true),
      styleSheet
    );
  }
 }

 connectedCallback() {
const onrampModal = document.querySelector('pera-onramp-modal');

if (this.shadowRoot) {
    this.render();

    const step = onrampModal?.getAttribute('step');

    this.shadowRoot.getElementById("back-button")?.addEventListener("click", () => {
        onrampModal?.setAttribute("step", (Number(step) - 1).toString());
    }
    )

    this.shadowRoot.getElementById("next-button")?.addEventListener("click", () => {
        onrampModal?.setAttribute("step", (Number(step) + 1).toString());
    }
    )

    this.shadowRoot.getElementById("cancel-button")?.addEventListener("click", () => 
{
        onrampModal?.setAttribute("step", "0");
        }
    )
}
}

private render() {
navigationButtons.innerHTML = `
    <div id="navigation-buttons">
        <button id="back-button" class="navigation-buttons__button-back" >Back</button>
        <button id="next-button" class="navigation-buttons__button--next">next</button>
        <button id="cancel-button" class="navigation-buttons__button--cancel">cancel</button>
    </div>
  `;
}
}

Solution

  • I think the problem is the "step" is not being re-assigned each time you press the button. Maybe try something like this?:

    this.shadowRoot.getElementById("back-button")?.addEventListener("click", () => {
        const step = onrampModal?.getAttribute('step');
        onrampModal?.setAttribute("step", (Number(step) - 1).toString());
    }
    )