1
<p onclick="play()">abc</p>

js

 function play(){
    do something; 
 }

The above works if js code is in the same file as p

But saying:

<script src="index.js"></script>

index.js

$(document).ready( function() {
     function play() {
        do something; 
     }
});

What i get is ReferenceError: play is not defined

Other functions, except play() works well.

Greg
  • 481
  • 1
  • 5
  • 21
qadenza
  • 9,025
  • 18
  • 73
  • 126

3 Answers3

4
$(document).ready(function(){
  function play(){
        do something; 
     }
});

play() function is local to $(document).ready(function(){ not global

Don't wrap your play function in $(document).ready(function(){ to keep it's scope global .

function play(){
    do something; 
}

Read Global and Local and Private Functions (Javascript)

and What is the scope of variables in JavaScript?

Community
  • 1
  • 1
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
3

This is due to scope.

play() isn't visible at that level, due to it being wrapped inside your $(document).ready function.

ahren
  • 16,803
  • 5
  • 50
  • 70
1

No need to place it in $(document).ready( function() {..}

just mention it in your index.js as

function play(){
  do something; 
}

remove $(document).ready( function() {

Naveen Kumar Alone
  • 7,536
  • 5
  • 36
  • 57