0

Is it possible to use onclick inside of a string literal?

I have a page view like so:

const page = () => {
  const htmlOutput = `
    <button
      onclick="openMessageComposer"
      id="messageCta">Message</button> // Using the id works
  `;
  document.getElementById('app').innerHTML += htmlOutput;
  document.getElementById('messageCta').onclick = () => {
    console.log("openMessageComposer")
  }
}

export default page;

It's being used in a router like so:

import page from './page.js';

window.onload = () => {
  page()
}

which is imported in my index.html file as a module as <script type="module" src="router.js"></script>

This works.

However, I'd like to avoid document.getElementById('messageCta').onclick. Is there a way to use the onclick event instead?

Something like

const openMessageComposer = () => {
  console.log("openMessageComposer")
}

which would exist inside the page component.

0

1 Answer 1

1

You currently have two onclicks: one, in the inline attribute, which tries to reference a global variable named openMessageComposer but then does nothing with it. (your other is your .onclick) If you want to remove the .onclick, then just make sure the inline handler invokes the openMessageComposer function instead:

onclick="openMessageComposer()"

But inline attributes are generally considered to be pretty poor practice, and can make scripts significantly more difficult to manage, especially in larger codebases - I'd prefer your current method of assigning to the onclick property of the element.

If it's the requirement of adding the id to the appended element that you don't like, then create the element explicitly with createElement instead, so you have a direct reference to it, without giving it an id, and assign to its onclick property:

const page = () => {
  const button = document.createElement('button');
  button.textContent = 'Message';
  button.onclick = openMessageComposer;
  document.getElementById('app').appendChild(button);
};
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the detailed reply! Using onclick="openMessageComposer()" didn't seem to work either when I was experimenting, unfortunately. I was aware of creating the button tag explicitly, but I think that's unnecessary since referencing the id works just fine. I was trying to implement a more functional method (like React) of assigning the onclick event to a method. Using the onclick property of the element the way I have it seems to be the only way that works.

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.