Issue
** I am learning Dom manipulation and it's my second day... how can I make it as a function that will generate random index of color which I already stored in my array. **
const btn = document.getElementsByClassName("btn");
const color = document.getElementsByClassName("color")
btn.addEventListener('click', function() {
const randomNumber = getRandomNumber();
document.body.style.backgroundColor = colors[randomNumber]
color.textContent = color[randomNumber]
})
function getRandomNumber() {
return Math.floor(Math.random() * colors.length);
}
<div class="btn">Click Me </div>
Solution
the getElementsByClassName
return an array of elements (cf doc).
to get the first element you should either get the first element of the array document.getElementsByClassName("btn")[0];
or add an id to the button and get it with the document.getElementById('myButton')
function
const btn = document.getElementsByClassName("btn")[0];
const color = document.getElementsByClassName("color")
btn.addEventListener('click', function() {
const randomNumber = getRandomNumber();
document.body.style.backgroundColor = colors[randomNumber]
color.textContent = color[randomNumber]
})
function getRandomNumber() {
return Math.floor(Math.random() * colors.length);
}
<div class="btn">Click Me </div>
Answered By - RenaudC5
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.