The functionality of a button within a web component is restricted to only trigger the click event once after it has been

I am facing an issue with my class that includes three buttons for navigating the app. The event listeners I add to these buttons in the connectedCallback method only work once. When I click one of the buttons, like the next button, it changes the attribute of another element as expected. However, when I try to click and navigate to a new screen, it stops working. Even in the inspector, the events are still attached to the buttons but they do not respond.

Is there something I am missing? I suspect it could be related to the shadow DOM, but I haven't been able to figure it out.

Thank you 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>
  `;
}
}

Answer №1

It could be possible that the issue lies in the fact that the variable "step" is not being updated each time the button is clicked. You may want to consider modifying your code like this:

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

Answer №2

If you're looking to tidy up your code, consider the following:

<count-buttons></count-buttons>
<script>
  customElements.define("count-buttons", class extends HTMLElement {
    constructor() {
      const tag = (name,props) => Object.assign(document.createElement(name), props);
      super()
        .attachShadow({mode:"open"})
        .append(
          tag("style", {
            innerText: `button{color:green;font-weight:bold}` +
                       `#back{color:red}` +
                       `span{margin:1em;font:21px Arial}`
          }),
          tag("button", {
            id: "back",
            innerText: "Back",
            onclick: (evt) => this.step--
          }),
          this.span = tag("span", {
            innerText: 0
          }),
          tag("button", {
            innerText: "Next",
            onclick: (evt) => this.step++
          }),
        )
    }
    get step() {
        return Number(this.span.innerText);
    }
    set step(value) {
        this.span.innerText = value;
    }
  });
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Alignment issue with Ul dropdown menus and shadow

After stumbling upon a fascinating menu design at this link, I decided to tweak it for center alignment by following the advice on this forum thread. Unfortunately, my efforts have hit a roadblock - the drop down menus aren't aligning as intended and ...

Mac users may experience lag when using Javascript parallax effects

I created a parallax page where the background image changes using JavaScript translateY(- ... px)' similar to what you see on the firewatch website. On Windows, the parallax effect works smoothly. However, on macOS it is smooth only in Safari. All ...

Dropping anchor whilst skipping or jumping

One of my website elements is a drop anchor that connects from a downwards arrow situated at the bottom of a full-page parallax image to another section on the same page. The HTML code snippet for the drop anchor is as follows: <section id="first" cla ...

Placing an icon to the left of the primaryText within the <ListItem> component of Material UI

Seeking to enhance a <ListItem> from React Material UI that currently displays a checkbox on the left side. My goal is to insert an image or icon between the checkbox and the title, positioned to the left of the title. Upon reviewing the documentatio ...

Sliding elements horizontally with jQuery from right to left

I recently purchased a WordPress theme and I'm looking to customize the JavaScript behavior when the page loads. Currently, my titles animate from top to bottom but I want to change this behavior dynamically. You can view it in action here: I have ...

Bring your images to life with a captivating 3D hover effect

I am looking to achieve a similar effect using JavaScript instead of just pure CSS like the example provided. I'd prefer not to use SCSS either, just sticking to CSS would be great. Please check out this CodePen for reference. .picture-container ...

Express.js post method malfunctioning for BMI calculation

Currently, I am working on a BMI calculator application in JavaScript as part of my practice. The app is supposed to take two inputs - weight and height, calculate the BMI, and display the result on the web page. However, after inputting the data and submi ...

Tips for asynchronously updating a model in TypeScript

I have been working on a function to hide the element for connecting to Facebook upon successful connection. I have implemented two functions, success and error, which trigger after Firebase successfully logs in the user. While I can confirm that these fun ...

Having trouble extracting the responseText from the Ajax request

My current challenge involves making an ajax call and receiving an Object in the response. However, when I attempt to access "responseText," it keeps returning as undefined: var results = API.get('users', { username: un, userpass: pw } ); conso ...

Create div elements using JSX and add them to an array

I am working with a structure that looks like this: var circle = { 'one': {items: []}, 'two': {items: []}, 'three': {items: []}, 'four': {items: []} }; Each items array needs to contain 10 unique ...

Masking the identity of Google Pagespeed

Just starting to learn the ropes of javascript. How can I make Google Pagespeed anonymous? Check out the original code here: http://pastebin.com/xRbTekDA. It's functioning properly when I visit the page. Here is the anonymized version: http://pasteb ...

What is the typical output value that fluctuates?

I only have one input to work with. My goal is to set the input value to "5", then display "3" in the "total" field and "4" in the "total2" field. Additionally, for every increment of +1 to the input value, I want the "total" and "total2" fields to also in ...

What causes the disparity in functionality between simple html and css in an Angular 2 project compared to a vanilla html website?

When incorporating the following html/css into a new Angular project created with Angular CLI using 'ng new ProjectName', I encountered issues. Despite adding the CSS to app.component.css or styles.css and the HTML to app.component.html, the Angu ...

An error occurred while attempting to retrieve data from a JSONArray

I have been working on creating a phonegap plugin for Android where I am returning a JSONArray using callBackContext.sendPluginResult(result);. Below is the code snippet demonstrating how I am constructing the JSONArray: private JSONArray makeJsonObject(S ...

Creating a jsp page content with jquery and retrieving request parameters

I am facing an issue with my JSP page where I need to pass the value of request.getParameter("cfgname") to another content page so that it loads correctly. Currently, the code is displaying null instead of the parameter. This is the main JSP page with par ...

Interactive Vue tree view featuring draggable nodes

I am currently working on creating a tree component in Vue.js, and I am facing challenges with implementing drag and drop functionality in the Tree component. I am unsure where to begin, as I have looked through similar code on GitHub but I am struggling t ...

Translate a portion of a painting by utilizing context.putImageData()

I am attempting to gradually fill a canvas with pieces of the original image. To achieve this, I need each square of the image to be filled in iteratively on the canvas. To optimize performance, my approach involves rendering the original image onto an of ...

Encountering the issue of "unexpected error: autocomplete is not defined" when trying to retrieve information

I am using jQuery for retrieving remote data but encountering an error Uncaught TypeError: $(...).autocomplete is not a function. I have made several attempts, yet I cannot identify the root cause of this issue. It seems like there might be an error in ...

Discover which npm module includes the lodash dependency

I've encountered a peculiar situation while using webpack to create a production bundle for my application. Even though I haven't explicitly installed `lodash` and it's not listed in my package.json file, I noticed that it's being added ...

How can I implement a loop using .then in JavaScript?

Looking to understand the .then concept in JavaScript, I am curious if it is feasible to generate a series of .then's using a for loop. request.send(myRequest) .then(r => console.log(r, 0)) .then(r => console.log(r, 1)) .then(r => ...