2

When I run any of my functions with the onClick="functionName()" property on a HTML element, it says functionName is not defined.

But it is defined!

function functionName() {
    //functional stuff
}

I also tried:

$(document).ready(function() {
    function functionName() {
        //functional stuff
    }
})

but that had no effect

In the html file, the button is here

html body div table tbody tr td button

and the script tag is here

html head script

Someone please explain to me why this is happening.

Indiana Kernick
  • 5,041
  • 2
  • 20
  • 50
  • 1
    Is your JavaScript file being loaded correctly? Are you defining the function in the scope of some other function? This is not enough code to determine what might be wrong. – Sam Hanley Oct 19 '14 at 03:11
  • 1
    Provide all your page code. – GramThanos Oct 19 '14 at 03:12
  • 2
    In the second example the function will not be available in the global scope. As of the first one - not enough information, show more code. – Cheery Oct 19 '14 at 03:16

1 Answers1

0

OnReady should fail because the parser created an event handler as the onClick attribute parsed. In this case the click event is being pointed to a non existent (null) function reference.

Represented By this fiddle http://jsfiddle.net/muglio/gzeksLr5/1/ (FAILS)

The second fiddle represents inline javascript in the head tag. In this case the browser would have already parsed and added functionName to the DOM before it reaches the onClick attribute.

Works http://jsfiddle.net/muglio/LoL9Ldzr/1/

If you then took that same script and put it in an external file "functionName.js" and called loaded it in the same place in the head you would create the potential for a race condition.

The script could be loaded before or after the onclick attribute is parsed. No guarantee.

In general you should avoid inline javascript for the same reasons you want to avoid inline css. You should setup the onclick handlers in javascript to avoid coupling your controller and view together.

<script>
    //Using jquery here because it is clearly being used in the initial ask :)
    $(document).ready(function(){
      function functionName() {

      }

      $('#myButton').on('click',functionName);
   });
</script>

html body div table tbody tr td <button id="myButton"></button>

Hope this helps you out.

muglio
  • 2,048
  • 17
  • 18