user3451039
user3451039

Reputation: 196

jquery not running when linked to an external js

Whenever I put the script in another file in the same folder as script.js, it doesn't run. It only runs when I include my code in the script tag.

I tried it out with this simple jquery code. Whenever the third script tag is uncommented, it works, but the set up I have right now doesn't run.

HTML

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script type="text/javascript" scr="script.js"></script> // <!-- doesn't run -->
    <!--script> // <!-- only runs inside the html file -->
        $(document).ready(function(){
            $('p').click(function(){
                $(this).hide();
            });
        });
    </script-->
</head>
<body>
    <p>Click to hide.</p>
</body>
</html>

script.js

$(document).ready(function(){
    $('p').click(function(){
        $(this).hide();
    });
});

Does anyone know what I am doing wrong?

Upvotes: 0

Views: 47

Answers (2)

risingPhoenix1979
risingPhoenix1979

Reputation: 1144

Your jQuery code is being duplicated inside the script.js file and .html file so that's why the code won't run.

Remove the jQuery code from the .html file and your code will run. Also like was mention above replace scr with src in your .html file.

Finally, I'd replace the code in your script.js file with the new code listed below as click(function(){} is older code:

$(document).ready(function(){
    $("p").on("click", function(){
        $(this).hide();
    });
}); 

Upvotes: -1

Quentin
Quentin

Reputation: 943150

scr is not src. Use a validator to make sure you haven't misspelt attribute names.

Upvotes: 5

Related Questions