0

I'm pretty new to jQuery, and I have the following function:

$('#new-game').click( evt => {
    evt.preventDefault();

    console.log("HELP ME");
    alert('button');
    startGame();
});

This function works when I copy it into the Google inspector console, but nothing happens when I click the button without first adding the function to the console.

<!-- jQuery ---------------------------------->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>

    <!-- JS ----------------------------->
    <script src="/js/grammarian.js"></script>

As you can see, my js file is after my jQuery, so I'm not sure why this is happening.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 1
    Most likely you're executing the code before the body and all its elements exist. – Teemu Mar 03 '20 at 18:20
  • Related: https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element – Taplar Mar 03 '20 at 18:24
  • 1
    Your jQuery and UI versions are ancient. You should investigate whether you can upgrade. It's usually fairly painless (directly converting `live()` to `on()` is 95% of the battle). – isherwood Mar 03 '20 at 18:40
  • 1
    also in modern JS (well, "modern"... every browser since 2012) you load scripts that modify the DOM using the `defer` attribute, so ``. This will load your script as usual but won't _run_ it until the DOM is ready for polling/manipulating. – Mike 'Pomax' Kamermans Mar 03 '20 at 21:33

0 Answers0