1

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?

3
  • 1
    Are you loading the example.js file before the #start element exists on the page? You should be loading the js file at the end of the page, or put the click handler within a document ready call. Commented Nov 21, 2015 at 16:34
  • @j08691 how can I load the js file at the end of the page? Commented Nov 21, 2015 at 16:56
  • 1
    Move <script type="text/javascript" src="example.js"></script> to right before </body>. Commented Nov 21, 2015 at 16:58

4 Answers 4

6

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.

Sign up to request clarification or add additional context in comments.

Comments

2

Try loading "example.js" at .ready() using $.getScript()

$(function() {
  $.getScript("example.js")
})

Comments

1

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>

1 Comment

Please note that I've embed the JQuery library just before </body>.
0

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.