Skip to content
Advertisement

I tried moving my JS script into a separate js file, but it stopped working once I did. How can I fix it?

I just started learning JS, and im not understanding it that well. I am not that great at coding generally, so apologies for this really barebones and very possibly wrong website, but all I wanted to accomplish at the moment was to change the websites background color when I press the button. When I did it in <script< it worked, but when I moved it into a separate JS file, it stopped working. The error message I get is: SyntaxError: Unexpected token ‘}’. Expected an opening ‘{‘ at the start of a function body. Could someone please help? Thank you in advance!

function makeRed() {
  document.getElementById('temp').style.backgroundColor = 'lightsalmon';
}

let btnRed = document.getElementById = ('btnRed');


btnRed.addEventListener("click", makeRed);
body {
  background-color: lightyellow;
  text-align: center;
  padding: 0;
  margin: 0;
}

.temperature {
  color: darkgoldenrod;
  font-family: Optima, sans-serif;
}

input {
  border: none;
  border-bottom: 2px solid darkgoldenrod;
  background-color: lightyellow;
  width: 50px;
}

input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

#header {
  background: darkgoldenrod;
  font-size: 20px;
  color: lightyellow;
  font-family: Optima, sans-serif;
}
<html>

<head>
  <title>Sun tester</title>
  <link rel="stylesheet" href="stylesheet.css">
  <link rel="icon" href="https://external-content.duckduckgo.com/iu/?u=http%3A%2F%2Fcdn.onlinewebfonts.com%2Fsvg%2Fimg_40038.png&f=1&nofb=1" type="image/x-icon">
</head>

<body>

  <div id="header">
    <h1 id="h1">Sun Tester</h1>
  </div>

  <div class="temperature">
    <p id="temp2">Temperature:
      <input type="number" id="temp"> °C</p>
  </div>

  <button type="button" id="btn-Red">Click Me!</button>

  <script src="script.js"></script>
</body>

</html>

Advertisement

Answer

you are assigning both btnRed and the document.getElementById method to a String value 'btnRed' instead of actually running the getElementById method and passing it an argument "btnRed"

so just change the let btnRed = document.getElementById = ('btnRed'); to let btnRed = document.getElementById('btnRed');

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement