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

          Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

          Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

          Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved