Reputation: 71
I want to implement a button which changes the background colour and text colour instantly. The colours are predefined in an array.
Code Snippet
<?php
include 'src/wordlist.php';
include 'src/colorcodes.php';
$result1 = $one[array_rand($one)] . " " . $two[array_rand($two)];
$colormix1 = $colors[array_rand($colors)];
$colormix2 = $colors[array_rand($colors)];
if ($colormix1 == $colormix2) {
$colormix2 = $colors[array_rand($colors)];
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body style="background: <?php echo $colormix2; ?>;">
<div class="table_1">
<table>
<tr>
<th>
HEADER
</th>
</tr>
<tr>
<td>
<p style="color: <?php echo $colormix1; ?>;">» <?php echo $result1; ?>. «</p>
</td>
</tr>
</table>
</div>
</body>
</html>
How can I achieve this with only JavaScript?
Thanks in advance!
//EDIT:
I found a solution:
function changeBackground() {
var colormix1 = colorcodes[Math.floor(Math.random() * colorcodes.length)];
var colormix2 = colorcodes[Math.floor(Math.random() * colorcodes.length)];
if (colormix1 == colormix2) {
var colormix2 = colorcodes[Math.floor(Math.random() * colorcodes.length)];
}
document.getElementById("quote").style.color = colormix1;
document.getElementById("footer").style.background = colormix1;
document.getElementById("ft-button").style.backgroundColor = colormix1;
document.getElementById("ft-button").style.color = colormix2;
document.getElementById("background").style.background = colormix2;
}
</script>
By calling the elements by their Id it worked just fine.
Upvotes: 0
Views: 74
Reputation: 1080
It is fairly simple to achieve this in JS. Please refer DOM API for more details
Run this Code Snippet for a demo
function changeBackground(value) {
var bgElement = document.getElementsByClassName('background')[0];
var textElement = document.getElementsByClassName('text')[0];
if (bgElement) {
bgElement.style.background = value;
}
if (textElement) {
textElement.style.color = value;
}
}
.background {
width: 100vw;
height: 100vh;
background: #000;
}
.dropdown {
width: 150px;
height: 32px;
margin: 16px;
}
.text {
font-size: 16px;
color: #000;
margin: 16px;
}
<div class="text">
This is some text
</div>
<div class="background">
<select class="dropdown" onchange="changeBackground(value)">
<option value="#F44336">Red</option>
<option value="#E91E63">Pink</option>
<option value="#9C27B0">Purple</option>
<option value="#673AB7">Deep purple</option>
<option value="#3F51B5">Indigo</option>
<option value="#FFFFFF">White</option>
<option value="#000000">Black</option>
</select>
</div>
Upvotes: 1