-5

I wrote a small page with jQuery and an external .js file. But it won't load the jQuery part. Here my Code:

<!DOCTYPE html>
<head>
    <script src="js/jquery-1.11.1.min.js"></script>
    <script src="js/testScript.js"></script>         
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
    <button id="testBtn">Oh my Goood...</button>                
    <div id="testDiv">testText</div> 
</body>
</html>

And here is my external Script:

alert("no jQuery");
$("button#testBtn").click(function(){
    alert("Works!");
});

As you can see, jQuery will load before all other scripts. The alert pops up fine. But if I click the button, nothing happens. If I put the script inside the html document directly, the button event works as expected.

I reviewed these questions: Link and Link. But still not working as expected.

Community
  • 1
  • 1
Marco Rehmer
  • 1,033
  • 2
  • 12
  • 32
  • 1
    You are adding a click event before the element is on the page. It is like eating a pizza before you make it. Learn about document ready. – epascarello Aug 10 '14 at 00:15
  • Check this question: https://stackoverflow.com/questions/13997299/jquery-events-working-only-in-document-ready – Gary.S Aug 10 '14 at 00:17

2 Answers2

2

Instead of using the $(document).ready() method, you could also just move your javascript references to the bottom of the page, right above the </body> tag. This is the recommended way to include javascript in webpages because loading javascript blocks the page rendering. In this case it also makes sure the elements are already rendered when the javascript is executed.

mwijnands
  • 1,236
  • 13
  • 22
  • I don't believe this is the wisest advice is it? If he is doing actions on dom elements i'd expect that they occur after the dom is fully loaded. The location if its the head or not is irrelevant in this matter. He could easily have code in the head that is called when the dom is loaded. – Scott Mitchell Aug 10 '14 at 03:00
  • It is often unnecessary. The best advise is to understand what you're doing and why. So read this: http://stackoverflow.com/questions/4643990/is-document-ready-necessary – mwijnands Aug 10 '14 at 08:03
0

You'll need to add the click function inside document ready.

$(document).ready(function(){
    $("button#testBtn").click(function(){
       alert("Works!");
    });
});

Your method fails because the code is being executed as the page is being loaded and the elements it refers to haven't been loaded yet. Using $(document).ready holds the function execution till the DOM elements are ready.

Newtt
  • 6,050
  • 13
  • 68
  • 106