2

I'm getting started with jQuery. I'v been trying to mix it with some of my preexisting JavaScript code so I don't have to rewrite everything. I have read many places that this is totally doable. However, whenever i include any lines of jQuery the standard JavaScript stops functioning.

Here's a few examples:

<!DOCTYPE html>
<html>
    <head>
        <style>
            #testjquery {
                height: 300px;
                width: 300px;
            }
        </style>
    </head>
    <body>
        <div id="testjquery" onclick="testClick()">This is the stuff.</div>
        <script src='jquery-1.10.2.min.js'></script>
        <script>
            $(document).ready(function() {
                function testClick() {
                    document.getElementById("testjquery").style.background = "blue";
                }
            });
        </script>
    </body>
</html>

This doesn't work, and when clicks I get a function not defined error.

But, putting this in the body

<body>
    <div id="testjquery">This is the stuff.</div>
    <script src='jquery-1.10.2.min.js'></script>
    <script>
        $(document).ready(function() {
            $("#testjquery").click(function() {
                $(this).css("background", "blue");
            });
        });
    </script>
</body>

Works fine, as does the equivalent in standard JavaScript.

Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
Nathan J
  • 195
  • 10
  • 2
    When you define "testClick" *inside* the jQuery "ready" handler, it's a *local function* and not visible in the global scope. – Pointy Nov 10 '13 at 16:45

2 Answers2

9

Don't wrap your function in DOM ready($(document).ready(function(){) handler.As it is a anonymous function so your testClick() function has local scope.So you can not call it outside the DOM ready

function testClick() {
    document.getElementById("testjquery").style.background = "blue";
}

Read What is the scope of variables in JavaScript?

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

The following block is run when the document is ready, and creates a local function testClick() that is not visible outside of the anonymous function (the one created by function(){ on the first line).

$(document).ready(function(){ 
function testClick(){
document.getElementById("testjquery").style.background="blue";
}
});

If you want to define a global function that can be called directly, you shouldn't put it inside a document ready handler. Change it to this instead.

function testClick(){
  document.getElementById("testjquery").style.background="blue";
}
Anders Abel
  • 67,989
  • 17
  • 150
  • 217