Search code examples
javascripthtmlfunctiononclickcodesandbox

Button onclick result: "'Function' is not defined" in HTML


I am using CodeSandbox to write up a localized access point for my social media (just to have fun with the Vanilla parcel pack they have). Now, I have my buttons calling separate functions, but when I select a button, the error "Function is not defined"

My functions for the buttons are stored in a separate file than the regular JavaScript.

I have looked on W3Schools to see how this is done. Several times I tried even putting the function within the HTML page itself to see if that helps; however, the error still appeared.

Below is an HTML example:


<button type="button" onclick="sShowFunction()">
          Discord Status
        </button>
        <br />
        <p id="dshow">Reveal Discord Status</p>
        <script src="extras/buttons.js" type="text/javascript"></script>

This is the js function:


function sShowFunction() {
  document.getElementById("dshow").innerHTML = `
  <iframe src="https://discordapp.com/widget?id=<server id>&theme=dark" width="350" height="500" allowtransparency="true" frameborder="0"></iframe>
  `;
}

I expect the output when I press the button to display the discord widget. Instead, I produce the aforementioned error. My best guess is that I am missing a piece of code to call the function. In the console, I receive this error: sShowFunction' is defined but never used. (no-unused-vars)


Solution

  • depend where you have declare the function .. could be is not accessible .. from the html level

    be sure your js code is inside a valid scritpt tag

    <script>
      function sShowFunction() {
         document.getElementById("dshow").innerHTML = '
           <iframe src="https://discordapp.com/widget?id=<server id>&theme=dark" 
         width="350" height="500" allowtransparency="true" frameborder="0"></iframe>
      ';
      }
    </script>
    

    and don't use backtics for wrap string .. use quote