Reputation: 141
As for example: I wanna show random background colors by pressing a button. I greated variables which would result in a usual hex-code if I put the strings together... Only how can I write these random values into the CSS file? Is there any way?
I do not wanna change the class name, but what the class name contains as a style-value for background-color!
function changeColor() {
var content = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g"];
var one = content[Math.floor(Math.random()*content.length)];
var two = content[Math.floor(Math.random()*content.length)];
var three = content[Math.floor(Math.random()*content.length)];
var four = content[Math.floor(Math.random()*content.length)];
var five = content[Math.floor(Math.random()*content.length)];
var six = content[Math.floor(Math.random()*content.length)];
Upvotes: 0
Views: 79
Reputation: 1
You can use the onClick
event on the button press to call the
changeColor()
function.
<Button
onClick={event => {
event.preventDefault();
this.changeColor();
}}
>
Upvotes: 0
Reputation: 303
This is what we have the style attribute for
function change(){
var content = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g"];
var one = content[Math.floor(Math.random()*content.length)];
var two = content[Math.floor(Math.random()*content.length)];
var three = content[Math.floor(Math.random()*content.length)];
var four = content[Math.floor(Math.random()*content.length)];
var five = content[Math.floor(Math.random()*content.length)];
var six = content[Math.floor(Math.random()*content.length)];
document.getElementById("element").style.backgroundColor = "#"+one+two+three+four+five+six
}
<div id="element">
see the background
</div>
<button onclick="change()">change</button>
Upvotes: 2
Reputation: 927
If you want to change inline styles you can take a look at this page:
Changing HTML Style - To change the style of an HTML element, use this syntax:
document.getElementById(id).style.property = new style
The following example changes the style of a<p>
element:Example:
<html> <body> <p id="p2">Hello World!</p> <script> document.getElementById("p2").style.color = "blue"; </script> <p>The paragraph above was changed by a script.</p> </body> </html>
<!DOCTYPE html>
<html>
<body>
<h1 id="id1">My Heading 1</h1>
<button type="button"
onclick="document.getElementById('id1').style.color = 'red'">
Click Me!</button>
</body>
</html>
Or
<!DOCTYPE html>
<html>
<body>
<h1 id="id1" style="color: blue">My Heading 1</h1>
<button type="button"
onclick="document.getElementById('id1').style = 'color: red'">
Click Me!</button>
</body>
</html>
Upvotes: 4