Search code examples
javascripthtmlcssjsfiddle

Why isn't click event firing in this simple jsfiddle demo?


I'm trying to create a little demo on jsfiddle, but when I click the toggle button, the click event isn't firing, it says myclick is not defined.

I have looked at other answers which mention the No wrap solution, but I don't see such configuration option in jsfiddle right now.

The jsfiddle: https://jsfiddle.net/5j9qgbxa/4/


Solution

  • It seems that the javascript with type onload will create the javascript in the beginning of your jsfiddle as followed:

    window.onload=function(){
      function myclick(){
       alert("myclick");
      }
    }
    
    
    <YourHTML>
    

    In which case he will not recognize myclick() as this is created later on in the HTML and is not triggered with onload. What you can do to avoid this is as you can see in this jsfiddle: https://jsfiddle.net/cqL9t8mh/1/

    What I did here is, delete the onclick="myclick" in your button and replace it with and ID 'btnToggle'. Afterwards in the javascript section you can add an addEventListener of the type click on the ID 'btnToggle' to trigger your myclick function.

    Also what you asked in the commands of previous answer is following: enter image description here

    This will make it so your code layout well be like:

    <YourHTML>
    function myclick(){
       alert("myclick");
      }
    

    In which case your HTML is first created before your function and it is no longer in an onload so it will now be triggered every time you click your button.