How to make jQuery work outside the document.ready block

Saul Goodman May 19, 2019 Loading...

This tutorial will show you how to make jQuery work outsite the document.ready block.

First, take a look at the following code.

The “index.html” file:

<html>
<head>
    <script src="jquery.min.js"></script>
    <script src="script.js"></script>
    <title>jQuery Test</title>
</head>
<body>
    <button id="trigger">Click me and the magic will happen</button>
</body>
</html>

The “script.js” file:

$("#trigger").click(function(){
    alert("The magic has happened");
})

If you click on the button, nothing happen. You won’t see the alert box.

How to fix?

The solution is very easy. Just place the “script.js” file before “</body> ” instead of in the “<head>”.

<html>
<head>
    <script src="jquery.min.js"></script>
    <title>jQuery Test</title>
</head>
<body>
    <button id="trigger">Click me and the magic will happen</button>
    <script src="script.js"></script>
</body>
</html>

The magic will happen. It works!

avatar
Welcome to KINDACODE. Have a nice day and code well!