Thisis my first JS project and i cant figure out where i went wrong, i am trying to make a color flipper whre if you click a button it picks a random color from an array of colors and make that the background color.
const colors = ["green", "red", "rgba(133,122,200)", "#f15025"];
const button = document.getElementById("btn");
const color = document.querySelector(".color");
button.addEventListener("click", function () {
const randomItem = colors[getRandomItem];
document.body.style.backgroundColor = randomItem;
color.textContent = randomItem;
});
const getRandomItem = function () {
return Math.floor(Math.random() * colors.length);
}
<body>
<!-- javascript -->
<script src="app.js"></script>
<nav>
<div >
<h4>color flipper</h4>
<ul >
<li><a href="index.html">simple</a></li>
<li><a href="hex.html">hex</a></li>
</ul>
</div>
</nav>
<main>
<div >
<h2>background color : <span >#f1f5f8</span></h2>
<button id="btn">click me</button>
</div>
</main>
</body>
CodePudding user response:
In this line:
const randomItem = colors[getRandomItem];
you aren't calling the function. Put parentheses after you write its name: getRandomItem()
.
Snippet
const colors = ["green", "red", "rgba(133,122,200)", "#f15025"];
const button = document.getElementById("btn");
const color = document.querySelector(".color");
button.addEventListener("click", function () {
const randomItem = colors[getRandomItem()];
document.body.style.backgroundColor = randomItem;
color.textContent = randomItem;
});
const getRandomItem = function () {
return Math.floor(Math.random() * colors.length);
}
<body>
<!-- javascript -->
<nav>
<div >
<h4>color flipper</h4>
<ul >
<li><a href="index.html">simple</a></li>
<li><a href="hex.html">hex</a></li>
</ul>
</div>
</nav>
<main>
<div >
<h2>background color : <span >#f1f5f8</span></h2>
<button id="btn">click me</button>
</div>
</main>
</body>