0

On body load, the button click is triggered. This behavior is unwanted. What is causing the function to trigger?

<!doctype html>
<html>
  <head>
  <body onload="init()">
    <div class="btn"><button type="button" class="btn" id="reset" style="font-size:60px;">Reset</button></div>
    <script>
      function init() {
      $("#reset").click(sendStatus());
    }

    // FUNCTIONS 
    function sendStatus (){
      console.log("foo");
      }
    </script>  
    <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
  </body>
</html>
Ryderpro
  • 1,295
  • 9
  • 17
  • 2
    It's because you're passing the *result* of the function to the handler, not the *reference* of the function. Try `$("#reset").click(sendStatus);`. You should also place your code in a `$(document).ready(fn)` block instead of using an outdated `onload` attribute. – Rory McCrossan Feb 09 '16 at 16:36
  • That was very helpful - thank you. – Ryderpro Feb 09 '16 at 16:57

2 Answers2

0

You have a click event within the init function. You are calling that function within the onload attribute in the body tag.

Tim Wilson
  • 169
  • 6
0

There are few fundamental issues with your code.

  1. There is no document.ready function. Please use this instead of onload. Refer the below links to know the difference.

window.onload vs $(document).ready()

jQuery - What are differences between $(document).ready and $(window).load?

  1. In init function button click event, you are calling the function "sendStatus" instead of assigning it. Hence it is getting triggered immediately

I have modified the code as follows

 $(function() {

   function init() {
     $("#reset").click(sendStatus);
   }

   // FUNCTIONS 
   function sendStatus() {
     console.log("foo");
   }

     init();

 });

and here is the fiddle. https://jsfiddle.net/7nt4q6yt/1/

Community
  • 1
  • 1
Thangaraja
  • 811
  • 5
  • 17