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.