-2

I can get my jQuery to work when I add it to the HTML file. However, I want the onclick function to trigger changes via jQuery and it is not working, any ideas why?

let startButton = document.getElementById("start-button");
startButton.onclick = () => {
    if (currentlyPlaying === false) {
        gameInitiate()
    }
    $('document').on('click', function(){

        $(this).css('background-color', 'red');
    })
    
};
  • Does this answer your question? [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – CBroe Feb 08 '21 at 13:27
  • What errors do you get in the console? Also, you should probably not add event listeners within the listener for an event. – Heretic Monkey Feb 08 '21 at 13:28
  • Btw. such a mix of native JavaScript and jQuery syntax, is really rather ugly. You should do the element selection and event handling using the proper jQuery methodology here to begin with. – CBroe Feb 08 '21 at 13:28

1 Answers1

0

You need to execute your JS code after the DOM has loaded. As such you need to either place the <script /> tag referencing it just before the </body>, or you can put it in the <head>, but you need to wrap your JS code in a document.ready handler.

Regarding the code itself, note that if you've included a JS library in the page it's best practice to be consistent in its use. In addition you should not nest event handlers, and $('document') needs to be $(document). With all that said, try this:

jQuery($ => { // <- document.ready handler
  $('#start-button').on('click', e => {
   if (!currentlyPlaying) {
     gameInitiate();
   }
  });
  
  let $doc = $(document).on('click', () => {
    // perhaps check if currentlyPlaying is true here?
    $doc.css('background-color', 'red');
  });
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Hey, thank you so much, I'm not quite getting it to work but I think I get the logic now. I'll spend a little time with it now and see. Thank you! – William9601 Feb 08 '21 at 20:48