-3

I have a function in my <head>

$('document').ready(function () {
    function shout(msg) {
        alert(msg);
    }
});

And a button in the <body>

but I am getting function shout not defined .Why?I am using Firefox 25.

SO has many similar questions and I have tried all but no help.Except this one,which might solve my problem.I didn't get what the answer is talking about.Please anyone elaborate what he is talking about as the two fiddles ,in answer as well as the question are exactly same ,except some property changes on the leftside bar: onload and No wrap-in <head>

Or what might be the problem?

Community
  • 1
  • 1
Naveen
  • 7,944
  • 12
  • 78
  • 165

4 Answers4

1

Your function is visible in it enclosure that is the document.ready. If you move function out side document.ready then it will accessible in global scope.

function shout(msg)
{
      alert(msg);
}
Adil
  • 146,340
  • 25
  • 209
  • 204
1

Your function is defined inside an anonymous function, so it's name is limited to that scope. If you're trying to access it from the onclick attribute of a button that won't work, because names there look in the global scope.

You have two solutions:

One is to define the function outside $(document).ready(), so it will be in the global scope.

The other is to bind your click handler using jQuery rather than an inline attribute:

$(document).ready(function() {
    $("#somebutton").click(function() {
        shout("Button was clicked");
    });

    function shout(msg) {
        alert(msg);
    }
});
Barmar
  • 741,623
  • 53
  • 500
  • 612
0
$('document').ready(function {
    shout('message');
});

function shout(msg) {
    alert(msg);
}
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
Johan Öbrink
  • 143
  • 2
  • 8
0

Because the function is wrapped inside a parent function. The scope inside the function is not available outside of it.

Separate it instead -

function shout(msg) {
    alert(msg);
}

$('document').ready(function{
    shout('AWESOME');    
});
Mike-O
  • 844
  • 1
  • 11
  • 16