0

I'd like to change the styles of the paragraph every time a button is clicked below.

for some reason, I can't get onclick function to work on my external js file or am I doing something wrong?

here is my html code

<html>
<head>
  <script src="task1.js"></script>
  <style>
  #paragraph {
    padding: 10px;
    margin-bottom: 10px;
    background-color: silver;
    border: 1px dashed black;
    width: 30%;
  }
  </style>
</head>
<body>
<h1> Kenmour Ryan C. Noble </h1>
<p id="paragraph"> Click buttons below to change this text style. <br>
<p> <button id="button1"> Green </button>
<button id="button2"> Blue </button>
<button id="button3"> Mono </button>
<button id="button4"> Sans Serif </button>
<button id="button5"> Serif </button> </p>
</div>
</body>
</html>

and here is my external js file

 var green = document.getElementById("button1");
green.onclick = function() {
  var paragraph = document.getElementById("paragraph");
  paragraph.style.color = "green";
}

var blue = document.getElementById("button2");
blue.onclick = function() {
  var paragraph = document.getElementById("paragraph");
  paragraph.style.color = "blue";
}

var mono = document.getElementById("button3");
mono.onclick = function(){
  var paragraph = document.getElementById("paragraph");
  paragraph.style.fontFamily = "monospace";
}

var sansserif = document.getElementById("button4");
sansserif.onclick = function(){
  var paragraph = document.getElementById("paragraph");
  paragraph.style.fontFamily = "sans-serif";
}

var serif = document.getElementById("button5");
serif.onclick = function(){
  var paragraph = document.getElementById("paragraph");
  paragraph.style.fontFamily = "serif";
}
Ken
  • 31
  • 6
  • 2
    Your script is executing before the DOM has loaded, either wait for document readyState to be complete or place your script element just before the closing body tag – Zeb Rawnsley Nov 15 '17 at 20:39
  • getElementById is a `document` prototype, not a standalone method (unless defined somewhere else). Hence, you should be doing `document.getElementById` instead. https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById . The green variable, in your example, is undefined (like any other variable out of any function anyway) – briosheje Nov 15 '17 at 20:39
  • i did document.getElementById but it still isn't working – Ken Nov 15 '17 at 20:41

0 Answers0