-2

I am new to Jquery and HTML and not too sure why my JQuery script here doesnt work. Any help would be appreciated, have a good day!

<!DOCTYPE html>
<html>

<head>
  <title>Game</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script>
    $('#button1').click(function() {
      alert('button clicked');
    });
  </script>
  <link rel="stylesheet" type="text/css" href="style.css">

  <body>
    <h1 id="title"><b>GAME</b></h1>
    <div id="button1"><button type="button">Join Game</button></div>
  </body>
</head>

</html>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
jajaja234
  • 1
  • 2

1 Answers1

0

You need to wait for the document to be ready using $(document).ready():

$(document).ready(function(){
      $('#button1').click(function() {
           alert('button clicked');
      });
});

For the future, always write the scripts at the end of the document so that all the elements are rendered first.

Majed Badawi
  • 27,616
  • 4
  • 25
  • 48