How to use `onclick` inside javascript string literalHow do JavaScript closures work?How do I remove a property from a JavaScript object?Which equals operator (== vs ===) should be used in JavaScript comparisons?How do I redirect to another webpage?How do I include a JavaScript file in another JavaScript file?How do I make the first letter of a string uppercase in JavaScript?How to replace all occurrences of a string in JavaScriptWhat does “use strict” do in JavaScript, and what is the reasoning behind it?How to check whether a string contains a substring in JavaScript?How do I remove a particular element from an array in JavaScript?

Why doesn't Newton's third law mean a person bounces back to where they started when they hit the ground?

What would happen to a modern skyscraper if it rains micro blackholes?

Malcev's paper "On a class of homogeneous spaces" in English

Why is consensus so controversial in Britain?

Did Shadowfax go to Valinor?

What is a clear way to write a bar that has an extra beat?

Why does Kotter return in Welcome Back Kotter?

Can you really stack all of this on an Opportunity Attack?

Why are electrically insulating heatsinks so rare? Is it just cost?

What does it mean to describe someone as a butt steak?

Does an object always see its latest internal state irrespective of thread?

Do infinite dimensional systems make sense?

What's the point of deactivating Num Lock on login screens?

Arrow those variables!

How does one intimidate enemies without having the capacity for violence?

Why "Having chlorophyll without photosynthesis is actually very dangerous" and "like living with a bomb"?

RSA: Danger of using p to create q

Convert two switches to a dual stack, and add outlet - possible here?

High voltage LED indicator 40-1000 VDC without additional power supply

How can bays and straits be determined in a procedurally generated map?

How is it possible to have an ability score that is less than 3?

dbcc cleantable batch size explanation

Why can't I see bouncing of a switch on an oscilloscope?

Character reincarnated...as a snail



How to use `onclick` inside javascript string literal


How do JavaScript closures work?How do I remove a property from a JavaScript object?Which equals operator (== vs ===) should be used in JavaScript comparisons?How do I redirect to another webpage?How do I include a JavaScript file in another JavaScript file?How do I make the first letter of a string uppercase in JavaScript?How to replace all occurrences of a string in JavaScriptWhat does “use strict” do in JavaScript, and what is the reasoning behind it?How to check whether a string contains a substring in JavaScript?How do I remove a particular element from an array in JavaScript?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








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.










share|improve this question




























    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.










    share|improve this question
























      0












      0








      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.










      share|improve this question














      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.







      javascript module onclick string-literals






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 8 at 2:09









      FaridFarid

      347315




      347315






















          1 Answer
          1






          active

          oldest

          votes


















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





          share|improve this answer























          • 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.

            – Farid
            Mar 8 at 2:26












          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55055747%2fhow-to-use-onclick-inside-javascript-string-literal%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









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





          share|improve this answer























          • 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.

            – Farid
            Mar 8 at 2:26
















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





          share|improve this answer























          • 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.

            – Farid
            Mar 8 at 2:26














          1












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





          share|improve this answer













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






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 8 at 2:14









          CertainPerformanceCertainPerformance

          97.8k165887




          97.8k165887












          • 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.

            – Farid
            Mar 8 at 2:26


















          • 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.

            – Farid
            Mar 8 at 2:26

















          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.

          – Farid
          Mar 8 at 2:26






          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.

          – Farid
          Mar 8 at 2:26




















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55055747%2fhow-to-use-onclick-inside-javascript-string-literal%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          1928 у кіно

          Захаров Федір Захарович

          Ель Греко