1

I have to define different functions in my project and they all rely on jQuery, so I have to make sure that they are inside the document-ready function. When I place them there, I get the error described bellow. How can this be fixed? The jQuery lib seems to be included correctly.

In <head>:

<script src="js/lib/jquery-2.0.3.min.js"></script>

Javascript:

$( document ).ready(function() {
     function checkAvailability() {
        ...
     }
});

When I try to access the function later on, I get this error:

Uncaught ReferenceError: checkAvailability is not defined
nimrod
  • 5,595
  • 29
  • 85
  • 149
  • 1
    possible duplicate http://stackoverflow.com/questions/1055767/why-can-i-not-define-functions-in-jquerys-document-ready – Greenhorn Sep 25 '13 at 07:21
  • 1
    When are you calling `checkAvailability` – painotpi Sep 25 '13 at 07:22
  • better to put the function outside of `doc ready` – Jai Sep 25 '13 at 07:25
  • After a click on a button on the page, so by then it should be loaded. @Ram I tried that already, but it says `undefined is not a function`. @Tarun Pai, if I do this, `.serialize()` does not work. – nimrod Sep 25 '13 at 07:25
  • If they *rely on jQuery*, then they only need to be placed after the jQuery inclusion. Only if they need to wait for the DOM (and a function *declaration* hardly needs), they would need to be placed inside `ready`. – Bergi Sep 25 '13 at 07:26
  • @doonot: Please show us the code of how you attach the listener to the click event. – Bergi Sep 25 '13 at 07:27
  • @doonot okay then if you put your function outside of doc ready then it will work perfectly fine. Although i am not a big fan of inline events. – Jai Sep 25 '13 at 07:38

2 Answers2

0

It's a scoping issue...

$( document ).ready(function() {
     function checkAvailability() {
        ...
     }

    checkAvailability() // can be called here as the definition is in scope
});

checkAvailability() // Can't be called here

Instead, define your function outside the jQuery method...

function checkAvailability() {
   ...
}

$( document ).ready(function() {

    checkAvailability() // can be called here
});
checkAvailability() // Or here

Think of function declaration scope in the same way you would variable declarations.

Basic
  • 26,321
  • 24
  • 115
  • 201
0

I think you have to put all your event actions in the doc ready handler and functions you can put outside of it:

function checkAvailability() {
    ...
 }

$( document ).ready(function() {
  your click event should be here....
});
Jai
  • 74,255
  • 12
  • 74
  • 103