Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript function does not work within jquery $(document).ready block

I am trying to call a JavaScript function from an onclick trigger.

HTML section:

<div class="my_radio">
    <input type="radio" name="my_radio" value="1" onclick="my_func()"/>  first button
</div><!-- end of class my_radio -->

And the JavaScript code

<script type="text/javascript">
    $(document).ready(function(){
        function  my_func(){
            alert("this is an alert");
        }
    });
</script>

It does not work.

But if i keep the JavaScript function out of the $(document).ready() code, it works. Following is the relevant code snippet:

<script type="text/javascript">
    $(document).ready(function(){
        function  my_func111(){
            alert("this is an alert");
        }
    });

    function  my_func(){
        alert("this is an alert");
    }
</script>

1) Why does not the first JavaScript code snippet work?

2) How can I get the first JavaScript code snippet working ?

EDIT :

SO FAR AS I KNOW, $(document).ready() is executed when the web page loads completely. So how can I prevent my_func() to be active before or after the complete page-loading if I write my_func() outside $(document).ready()?

like image 934
Istiaque Ahmed Avatar asked Dec 22 '22 05:12

Istiaque Ahmed


2 Answers

It's all about javascript execution contexts and scope.

Everything that you define within a function is know only in this function.

In your first test, the function my_func() can only be used within the ready callback (and in the inner other objects). You can't reference it outside.

In your second example, the function my_func() is global to the document and accessible from anywhere.

I recognize this is maybe a verry simple explanation :-)

like image 82
Didier Ghys Avatar answered Jan 06 '23 00:01

Didier Ghys


If you define your function within a callback, you can only use it within this callback:

$(document).ready(function(){
  function something(){
    alert('test');
  }

  //..

  something(); // Will work
}

something(); // Won't work
like image 32
Sgoettschkes Avatar answered Jan 05 '23 23:01

Sgoettschkes