2

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);

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.