JavaScript TypeError : button is null but working fine in console typeerror button is null,typeerror button is null learn more

So I wanted to make a webpage in which on button click, the background color changes.

Its showing TypeError on loading in browser but its working fine after pasting same JavaScript on console.


Code snippet

var colors = ["#0af5fa", "#0ab1fa", "#0a3efa", "#560afa", "#b70afa", "#fa0ad9", "#fa0a65", "#fa0a1e", "#fa5e0a", "#facc0a", "#cbfa0a", "#69fa0a", "#0afa1b", "#0afa77", "#0afae5", "#0a8efa"];

var flag = 0,
  blinkCount = 0;

function blink() {
  if (blinkCount == 15) {
    blinkCount = 0;
    blink();
  } else {
    var h1 = document.querySelector("h1");
    var body = document.querySelector("body");

    h1.style.color = colors[blinkCount];
    body.style.background = colors[blinkCount];
    blinkCount++;
  }
}

var button = document.querySelector("button");
button.addEventListener("click", blink);
button {
  width: 50%;
  height: 100px;
  background: black;
  margin-top: 300px;
  margin-left: 300px;
}

h1 {
  color: #0af5fa;
}

body {
  background: #0af5fa;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<script src="../JavaScript/ex153.js"></script>
<link target='_blank' href="../css/ex153.css" rel="stylesheet">

<head>
  <meta charset="utf-8">
  <title></title>
</head>

<body>
  <div class="">
    <button><h1>Click Me</h1></button>
  </div>
</body>

</html>
Answer:1

When I click on the link << Add Call >> the modal is opened with custom URL but in the background is a blank view, I want the previous state to still appearing behind the modal when opened ...

When I click on the link << Add Call >> the modal is opened with custom URL but in the background is a blank view, I want the previous state to still appearing behind the modal when opened ...

  1. view previous state tax returns

I got a "show more" button thats works. The problem I'm having is, it uses the text from var text I want it to use it directly from HTML, any suggestions? var status = "less"; function ...

I got a "show more" button thats works. The problem I'm having is, it uses the text from var text I want it to use it directly from HTML, any suggestions? var status = "less"; function ...

str = prompt("enter a string"); rev = str.split("").join("").reverse(); console.log(rev); Guys, I am trying to reverse an array using the above code but I am getting an error stating "Type error ....

str = prompt("enter a string"); rev = str.split("").join("").reverse(); console.log(rev); Guys, I am trying to reverse an array using the above code but I am getting an error stating "Type error ....

This is my code. function m1() { return new Promise(function(resolve, reject) { var files = $('#aws-upload-files')[0].files; if (files.length > 0) { for (var i = 0; i < files....

This is my code. function m1() { return new Promise(function(resolve, reject) { var files = $('#aws-upload-files')[0].files; if (files.length > 0) { for (var i = 0; i < files....