Jquery and $(document).ready(function()

3.4k views Asked by At

I've read many things about $(document).ready(function() it's clear when it is usefull , so generally i write $(document).ready(function() inside

but , why the devil , why is it KO in this so simple case ? if you just put off le $(doc.... it works perfectly

code :

<?php
?>
<!DOCTYPE html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
        <script defer>
            $(document).ready(function(){
                //alert('ready boy');
            function changeText(id) {
                id.innerHTML = "Ooops!";
            }
            });
        </script>
    </head>
<body>

<h1 onclick="changeText(this)">Click on this text!</h1>



</body>
</html>
2

There are 2 answers

0
Rory McCrossan On

It's a scope problem. When using the outdated on* event attributes the function you call must be defined under the scope of the window. In your code example you've defined it within the scope of jQuery's ready handler.

To fix this you can either move the function to be directly within the <script> tag, and hence under the window scope:

<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
  <script defer>
    $(document).ready(function() {
      console.log('ready boy');
    });

    function changeText(id) {
      id.innerHTML = "Ooops!";
    }
  </script>
</head>
<body>
  <h1 onclick="changeText(this)">Click on this text!</h1>
</body>
</html>

Alternatively, and preferably, you could remove the on* event attribute and attach your event handler using unobtrusive Javascript instead:

<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
  <script defer>
    $(document).ready(function() {
      console.log('ready boy');

      $('h1').click(function() {
        this.innerHTML = "Ooops!";
        // $(this).text('Ooops!'); // alternative
      });
    });
  </script>
</head>
<body>
  <h1>Click on this text!</h1>
</body>
</html>

0
PeterKA On

First, I would advice against using inline JavaScript as it may be difficult to maintain the code. Thus you would not need a named function.

Secondly, the named function is not accessible globally, which is where the inline code is looking for it.

Here is a demo showing how you could approach this:

$(document).ready(function(){
    //alert('ready boy');
    $('h1.changeit').on('click', function() {
        $(this).text('Ooops!'); //.html('Ooops!')
        //OR this.innerHTML = "Ooops!";
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h1 class="changeit">Click on this text!</h1>