Search code examples
javascriptweb-applications

How would I get my toast action button to work with an assigned action?


I'm trying to create a toast notification with an action button attached to the message. How can I get the button to work when clicked in the UI?

I'd like the action event to do different things with other use cases, so keeping this modifiable is preferred.

export const ToastAction = {
    init() {
      this.hideTimeout = null;
  
      this.el = document.createElement("div");
      this.el.className = "toastAction";
      document.body.appendChild(this.el);
    },
  
    show(message, action, state) {
      clearTimeout(this.hideTimeout);
  
      this.el.className = "toastAction toast--visible";

      const text = document.createElement("p");
      text.textContent = message;
      this.el.appendChild(text);

      const button = document.createElement("button");
      button.textContent = action;
      this.el.appendChild(button);
  
      if (state) {
        this.el.classList.add(`toast--${state}`);
      }
  
    //   this.hideTimeout = setTimeout(() => {
    //     this.el.classList.remove("toast--visible");
    //   }, 5000);                  
    }
  };
  
  document.addEventListener("DOMContentLoaded", () => ToastAction.init());

// show toast message and button + add click event to button

    ToastAction.show("message", "Text", "success").onclick(alert("clicked!"))

Solution

  • Hope, I understand the problem right

      ..................
          if (state) {
            this.el.classList.add(`toast--${state}`);
          }
      
        //   this.hideTimeout = setTimeout(() => {
        //     this.el.classList.remove("toast--visible");
        //   }, 5000);  
          return button;                
        }
      };
    
    ToastAction.show("message", "Text", "success").onclick(() => alert("clicked!"))