-2

I have a very simple HTML file that looks like this:

<html>
    <head>
        <script src="jquery-1.11.1.min.js"></script>
        <script src="mainScript.js"></script>
    </head>
    <body>
        <button id = "theButton" type="button">Click Me!</button>
    </body>
</html> 

mainScript.js looks like this:

$("#theButton").click(function() {
  alert( "Handler for .click() called." );
});

Nothing happens when I click though. If I put an alert into the JS file it will happen. If I run that snippet of JS in the console, then when I click the button it will work. I've tested that jQuery is loaded, and it is. I've also put this code in JS Fiddle and it works (http://jsfiddle.net/ds59ruvu/). What stupid thing am i doing locally that's preventing this from working?

user3715648
  • 1,388
  • 3
  • 14
  • 24
  • And many more duplicates: [`[jquery] works in jsfiddle`](http://stackoverflow.com/search?q=%5Bjquery%5D+works+in+jsfiddle) – Felix Kling Sep 10 '14 at 18:27

2 Answers2

2

Wrap your code inside ready handler:

$(document).ready(function(){
  // your code here
});

OR,

$(function(){
  //your code here
});

OR, move your script file before the closing of body:

<html>
    <head>

    </head>
    <body>
        <button id = "theButton" type="button">Click Me!</button>
        <script src="jquery-1.11.1.min.js"></script>
        <script src="mainScript.js"></script>
    </body>
</html> 
Bhojendra Rauniyar
  • 78,842
  • 31
  • 152
  • 211
0

You should wrap your code with $(document).ready:

$(document).ready(function()
{
    $("#theButton").click(function()
    {
        alert( "Handler for .click() called." );
    });
});

The problem is in fact, that script is executed before element with id "theButton" is loaded, so you can't select it using $("#theButton").

Regent
  • 5,116
  • 3
  • 20
  • 35
  • `$(function() {});` for short :) – GillesC Sep 10 '14 at 18:22
  • 1
    @gillesc it looks very strange for people, who is just starting to work with JS and jQuery, so I usually don't mention this version :) – Regent Sep 10 '14 at 18:27
  • 1
    Agreed, just thought was worth mentioning, the long version is technically more appropriate as descriptive of what it does :) – GillesC Sep 10 '14 at 18:32