Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including jQuery causes standard JavaScript to stop functioning?

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.

like image 490
Nathan J Avatar asked May 11 '26 03:05

Nathan J


2 Answers

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?

like image 69
Tushar Gupta - curioustushar Avatar answered May 12 '26 18:05

Tushar Gupta - curioustushar


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";
}
like image 44
Anders Abel Avatar answered May 12 '26 18:05

Anders Abel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!