I've tried the following code:
<button id = "changeColor">Click here to change my color</button>
<script>
var changeButton = document.getElementById('changeColor');
function random(number){
return Math.floor(Math.random()*number);
}
function switchColor(){
var randomColor = 'rgb(' random(255) ',' random(255) ',' random(255) ')';
}
changeButton.addEventListener('click', switchColor);
</script>
but the button doesn't return any color upon clicking it.
Thanks a lot in advance for answering my question
CodePudding user response:
You need to change the color
in style
of the selected button with the genrated random color.
changeButton.style.color = randomColor
<button id = "changeColor">Click here to change my color</button>
<script>
var changeButton = document.getElementById('changeColor');
function random(number){
return Math.floor(Math.random()*number);
}
function switchColor(){
var randomColor = 'rgb(' random(255) ',' random(255) ',' random(255) ')';
changeButton.style.color = randomColor
console.log(randomColor);
}
changeButton.addEventListener('click', switchColor);
</script>
CodePudding user response:
<button id = "changeColor">Click here to change my color</button>
<script>
var changeButton = document.getElementById('changeColor');
function random(number){
return Math.floor(Math.random()*number);
}
function switchColor(){
var randomColor = 'rgb(' random(255) ',' random(255) ',' random(255) ')';
// CHANGE THE TEXT COLOR
document.getElementById("changeColor").style.color = randomColor;
}
changeButton.addEventListener('click', switchColor);
</script>
CodePudding user response:
Try This Way
Your Code Is Missing
changeButton.style.color = color;
var changeButton = document.getElementById('changeColor');
function random(min, max){
return Math.floor(Math.random() * (max - min 1)) min;
}
function switchColor(){
var color;
color = 'rgb(' random(0, 255) ',' random(0, 255) ',' random(0, 255) ')';
changeButton.style.color = color;
}
changeButton.addEventListener('click', switchColor);
button{ border: none; }
<button id = "changeColor">Click here to change my color</button>
CodePudding user response:
To keep it more precise, try this
var changeButton = document.getElementById('changeColor');
changeButton.onclick= () => {
var randomColor = 'rgb(' Math.random()*255 ',' Math.random()*255 ',' Math.random()*255 ')';
changeButton.style.color = randomColor
}
<button id = "changeColor">Click here to change my color</button>