Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    Sep 2011
    Location
    UK, South Wales, Newport
    Posts
    21
    Thanks
    8
    Thanked 0 Times in 0 Posts

    function syntax error??

    why does my javascript function run right away when the page loads? but not wen the button is clicked? its working the opposite to how i want it to
    i didnt include the other html tags to help focus on this.
    Btw im tryna avoid the method of having the onclick="funct()" method which would be written in the button tag. Thank you.

    <body>
    <button id="mybutton">Click me</button>
    </body>

    <script type = "text/javascript">
    var b = document.getElementById("mybutton");
    b.onclick = funct()

    function funct()
    {
    alert("Thanks for clicking me!");
    }
    </script>

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,664
    Thanks
    80
    Thanked 4,641 Times in 4,603 Posts
    Code:
    <script type = "text/javascript">
    // function defined first, so the assignment below knows what it is
    function funct()
    { 
        alert("Thanks for clicking me!"); 
    }
    var b = document.getElementById("mybutton");
    // assign the *function* to the onclick, *NOT* the result of CALLING the function 
    b.onclick = funct; 
    
    </script>
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    samz (09-15-2011)

  • #3
    New Coder
    Join Date
    Sep 2011
    Location
    UK, South Wales, Newport
    Posts
    21
    Thanks
    8
    Thanked 0 Times in 0 Posts
    you sir are a LEGEND


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •