Reputation: 1573
My external js file (example.js):
alert("External js file has just been loaded !");
$("#start").click(function (e) {
alert("Starting !");
});
My HTML file has <script type="text/javascript" src="example.js"></script>
.
When I load the page, it alerts "External js file has just been loaded !"
, which means the js file is successfully loaded.
However, when I click to the Start button, it doesn't alert "Starting !"
.
When I insert content of example.js file to the html file, it can alert "Starting !"
:
<script>
alert("External js file has just been loaded !");
$("#start").click(function (e) {
alert("Starting !");
});
</script>
How can I fix such a problem with the external js file?
Upvotes: 1
Views: 3121
Reputation: 364
Make sure that you have injected your jquery
script before your example.js
.
For Example:
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="example.js"></script>
And check your console if you are getting any errors.
Upvotes: 6
Reputation: 3104
I've just tried this and everything seems to work fine.
$(document).ready(function() {
$("#world-button").click(function() {
alert("Hello World");
});
});
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Demo</title>
</head>
<body>
<button id="world-button">Hello World</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</body>
</html>
Upvotes: 1
Reputation: 1
Try loading "example.js"
at .ready()
using $.getScript()
$(function() {
$.getScript("example.js")
})
Upvotes: 2
Reputation: 15699
It is happening because you have not written click event inside document.ready function. Events should be written when DOM is ready.
$(document).ready(function(){
$("#start").click(function (e) {
alert("Starting !");
});
});
You can find more details here: https://learn.jquery.com/using-jquery-core/document-ready/
Upvotes: 0