-2

I'm try to create a clickable button in my webpage using Javascript, First i'm writing index.html (html, css, javascript all together) then it was work fine. Here is my first code:

  <!DOCTYPE html>
   <html>
  <head>
    <title>LearnVariable</title>
   <link rel="stylesheet" type="text/css" href="style.css">
  </head>
<body>
    <button>PressMe</button>
    <script>
        var button = document.querySelector('button');
        button.onclick = function(){
            var name = prompt('What is your Name');
        }
    </script>
 </body>
 </html>

Then i'm try to write my javascript code in different file name script.js and Link this file with head section and cut my script part from body section .Then it occur a error that say that TypeError: button is null . Here is my index.html code :

 <!DOCTYPE html>
 <html>
  <head>
    <title>LearnVariable</title>
    <script src="script.js"></script>
    <link rel="stylesheet" type="text/css" href="style.css">
  </head>
  <body>
    <button>PressMe</button>
  </body>
 </html>

And This is my script.js code:

var button = document.querySelector('button');
button.onclick = function(){
var name = prompt('What is your Name');
}

I'm try to find the bug by myself and search internet then they said that use console.log(button) to figure out the error, but i didn't find how to solve this.

Rafsan
  • 151
  • 1
  • 9
  • In the second case, your browser is trying to execute the script while the page is still loading. Because it hasn't loaded the button on the page yet, button is null. You can either put your script at the end of the page, or you can place it inside a function that only executes after the page is completely loaded. jQuery provides `$(document).ready();` for such an occurrence. – bcr666 Mar 14 '18 at 21:48

1 Answers1

1

The problem is that you are calling the code before the document is initialized. To fix this problem, just put the script at the bottom of the page:

<!DOCTYPE html>
<html>
    <head>
    <title>LearnVariable</title>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
    <button>PressMe</button>
    <script src="script.js"></script> <!-- the script is here instead -->
</body>
</html>

edit: as @Brianbcr666Ray said, it is reccommended to load the script when the document is loaded. For instance, the following can be your script.js:

window.onload = function() {
    console.log("Do stuff here");
}
TheGreatRambler
  • 128
  • 2
  • 10
  • Thanks , Now it is work. Just before now i think that if i link my script code in head section then it load all the code when and where it need. – Rafsan Mar 14 '18 at 21:56