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

228
Views
How to use onClick function inside innerHTML

This is my JS file, it is one of reusable HTML components since I'm not using any framework. Before this I'm using ReactJS, since for some reason, I required not to use any framework for frontend.

My question is I want to make onClick function for the button. I thought it is the same thing as using JSX in ReactJS but it doesn't work. I want to add the <script> tag in the innerHTML but I don't think it is relevant because this is already a javascript file.

class Header extends HTMLElement {
    connectedCallback() {
        this.innerHTML =
           `
             <button onclick="">Try it</button>
           `
    }
}

customElements.define('main-header', Header);
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

<button onclick="fn()">Try it</button>
Or you can write code in the quotes directly:
onclick="console.log('click')"

about 4 years ago · Juan Pablo Isaza Report

0

HolaPz is correct, but to more clearly demonstrate-

function buttonClicked()
{
  console.log("You son of a gun, you did it");
}

class Header extends HTMLElement {
    connectedCallback() {
        this.innerHTML =
           `
             <button onclick="buttonClicked()">Try it</button>
           `
    }
}

customElements.define('main-header', Header);

NOTE: when buttonClicked is called, the "this" context will be set to the Window object and only top-level functions will be available. Depending on how you want to code going forward, it might make sense to use this.querySelector inside connected callback to get a reference to the button and then manually add a bound function or event listener (via addEventListener) to it.

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!