user3953989
user3953989

Reputation: 1929

Getting error ReferenceError for a function that is defined lower than it's usage

I've read that you should keep your Javascript at the very bottom of your page. However when I do this I get a ReferenceError: showDialog is not defined error since I'm referencing it before it's usage. I have it wrapped in document.ready but still doesn't work.

<a href="javascript:void(0)" onclick="showDialog()">Add New User</a>

$(function() {
    function showDialog() {
        $('#dialog-AddUser').show();
    }
}

Upvotes: 2

Views: 328

Answers (2)

S&#233;bastien
S&#233;bastien

Reputation: 12139

Your function is defined in the context of an anonymous function:

$(function () {
    function showDialog() {
        $('#dialog-AddUser').show();
    }
}

So showDialog cannot be called from outside the context of that anonymous function.

The solution here would be to add the click event handler from inside the function

$(function () {
    function showDialog() {
        console.log('clicked');
        $('#dialog-AddUser').show();
    }
    $('#my-clickable-link').click(showDialog);
});
<script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>
<a href="javascript:void(0)" id="my-clickable-link">Add New User</a>

Then ultimately you don't need the showDialog function, just another anonymous function as the click handler.

 $(function () {
    $('#my-clickable-link').click(function() {
      $('#dialog-AddUser').show()
    });
});
<script
      src="https://code.jquery.com/jquery-3.2.1.min.js"
      integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
      crossorigin="anonymous"></script>
<a href="javascript:void(0)" id="my-clickable-link">Add New User</a>

<div id="dialog-AddUser" style="display:none;">Hello!</div>

Upvotes: 2

Suresh Atta
Suresh Atta

Reputation: 121998

$(function () {
    function showDialog() {
        $('#dialog-AddUser').show();
    }
}

You got scope issues here. Not at all related to document loading. Remember that, whenever you declared/created something inside a function it is local to that function. Move it to outside where the whole document can see it.

Simply write

 function showDialog() {
            $('#dialog-AddUser').show();
        }

Should work.

Even if you write this function inside document ready, your function again localised to that particular ready function and become invisible to outside.

Upvotes: 3

Related Questions