Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

110
Views
Add eventListener or timeout to vanilla JS component after rendering?

I'm currently rendering a component in vanilla JS by calling a method attached to a class where the component is defined, and returned.

class ToastNotification {
  constructor(paramsObj) {
    this.notificationType = paramsObj.notificationType || "info";
    this.notificationAction = paramsObj.notificationAction || "none";
    this.title = paramsObj.title || "Something happened";
    this.message = paramsObj.message || `Here's some more specific information on what happened`;
  }

  getHtml() {
    return `
      <div
        class="toastNotification notification_${this.notificationType} ${this.enableAnimations()}"
      >
        <div class="notification_icon">
          <ion-icon name="${this.icon}"></ion-icon>
        </div>

        <div class="notification_text">
          <p class="text_title">${this.title}</p>
          <p class="text_message">${this.message}</p>
          <p class="text_time">${this.timeSinceNotification()}</p>
        </div>

        <div class="notification_close">
          <ion-icon name="close" onclick="this.closest('.toastNotification').remove()"></ion-icon>
        </div>
      </div>
    `;
  }
}

But how can I add an event listene or set a timeout to take an action on the component, after I have called the getHTML() method to render the element?

As I would like to be able to set a timeout for the rendered element to dissapear after X amount of time and add an event listener to enable different actions when clicked on. But I am open to alternatives if they can get the same job done.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The best result I've come up with so far is using the MutationObserver.

const observer = new MutationObserver((change) => {
    
  change[0].addedNodes.forEach( newNode => {
    
    if (newNode.tagName == 'DIV' && newNode.classList.contains('toastNotification')) {
    
        // Add listeners or do an action             
    }
  });
});

And then attaching the observer to the HTML document, or the body

observer.observe(document.querySelector('html'), {attributes: false, childList: true, subtree: true,});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!