-2

<button class="ordercolor" onclick="ordercolor()">Order Color</button> This is the button on HTML

var color = 
  ["#222f3e", "#dd260e", "#0ae196c", "#0ae127", "#0a7ce1", "#a60ae1", "#808000", "#00FF00", "#00FFFF", "#008080", "#FF5733"];
  var i = 0;
  addEventListener("click",
  function () {
  i = i < color.length ? ++i : 0;
  document.querySelector("body").style.background = color[i];

This is the script on Java.

That script applies on every button I got on HTML and I want it specific in one button. Can you help me apply it to the specific button ? Or maybe you have another script for changing colors in order on click, like green after red after blue (always the same) ?

Raul
  • 1
  • 2

1 Answers1

-1

You need to name the function. If you are using onclick you do not need to use the event listener. Like this:

<button class="ordercolor" onclick="ordercolor()">Order Color</button>
<script>
var color = ["#222f3e", "#dd260e", "#0ae196c", "#0ae127", "#0a7ce1", "#a60ae1", "#808000", "#00FF00", "#00FFFF", "#008080", "#FF5733"];
var i = 0;
function ordercolor() {
i = i < color.length ? ++i : 0;
document.querySelector("body").style.background = color[i];
}
</script>
Garbg
  • 47
  • 5
  • 1
    Huh? Your code listens for the click event of a button and handles it with the function `ordercolor`. That my friend, is an event listener. Your code merely connects the two via an inline statement ( onclick="...." ). This is virtually identical to using JS code to call `.addEventListener` (the *this* var will have a different value) – enhzflep Jul 08 '22 at 00:41