Search code examples
javascriptjsfiddle

JSFiddle does not manage click events inside a function


I have a very simple JSFiddle

HTML

<input type="button" value="Submit" id="myBtn" onclick="foo()">

JS

function foo(){
    console.log('click');

  $("#myBtn").click(function(event) {
    console.log('click2');
  });

    console.log('click3');

}

Here's the link: https://jsfiddle.net/mdvyo481/

I've already loaded the script in No Wrap - Head mode. Strangely, when I click on the button, click and click3 are printed in console but click2 is not printed. If I click on it again, I get 2 prints of click2.

Looks like event is not properly managed in the fiddle. Is there a way to fix?


Solution

  • This is correct behaviour. The reason this happens is because you bind the event click when you call the foo function. The first time you call foo you bind the event, the second time you bind it again and so on. Binding an event doesn't remove the previous bind, so if you click submit 10 times, you will bind 10 different click eventhandlers, all doing the same thing and you'll receive 'click2' 10 times in the console.