Random color each 5 seconds [duplicate] - javascript

This question already has answers here:
js get by tag name not working
(3 answers)
Closed 9 months ago.
I have the code for the random color that i took it from someone from here but i does not work when I try to put it in the h3 tag can anyone help me?
function generateRandomColor()
{
var randomColor = '#'+Math.floor(Math.random()*16777215).toString(16);
if(randomColor.length != 7) {
randomColor = generateRandomColor();
}
return randomColor;
// The random color will be freshly served
}
var h3 = document.getElementsByTagName("h3");
window.setInterval(function(){
h3.style.color = generateRandomColor()
}, 5000);

Your issue here is that your h3 variable refers to an HTMLCollection, not a single Element. For this reason, you need to loop over those elements, rather than trying to set the style directly on h3, like so:
function generateRandomColor()
{
var randomColor = '#'+Math.floor(Math.random()*16777215).toString(16);
if(randomColor.length != 7) {
randomColor = generateRandomColor();
}
return randomColor;
// The random color will be freshly served
}
var h3 = document.getElementsByTagName("h3");
window.setInterval(function(){
Array.from(h3).forEach(function (elem) {
elem.style.color = generateRandomColor();
})
}, 5000);
<h3>Test</h3>
<h3>Test2</h3>
<h3>Test3</h3>
If you want them to all be the same color, you would just move the generateRandomColor() outside the loop, like this:
window.setInterval(function(){
var color = generateRandomColor();
Array.from(h3).forEach(function (elem) {
elem.style.color = color;
})
}, 5000);

The problem is that you are trying to get all h3 on the page which returns a list of them. If you only want to change this for a single element then just change getElementsByTagName to querySelector like this.
function generateRandomColor()
{
var randomColor = '#'+Math.floor(Math.random()*16777215).toString(16);
if(randomColor.length != 7) {
randomColor = generateRandomColor();
}
return randomColor;
// The random color will be freshly served
}
var h3 = document.querySelector("h3");
window.setInterval(function(){
h3.style.color = generateRandomColor()
}, 5000);
<h3>Header!</h3>
If you want this to works for all h3 elements you could do it like this instead.
function generateRandomColor()
{
var randomColor = '#'+Math.floor(Math.random()*16777215).toString(16);
if(randomColor.length != 7) {
randomColor = generateRandomColor();
}
return randomColor;
// The random color will be freshly served
}
var headers = document.querySelectorAll("h3");
window.setInterval(function(){
for(var h3 of headers) {
h3.style.color = generateRandomColor()
}
}, 5000);
<h3>Header 1!</h3>
<h3>Header 2!</h3>
<h3>Header 3!</h3>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
h3 {
font-size : 45px;
}
</style>
</head>
<body>
<h3>Hi Good to see that </h3>
<script>
function generateRandomColor() {
var randomColor = '#' + Math.floor(Math.random() * 16777215).toString(16);
if (randomColor.length != 7) {
randomColor = generateRandomColor();
}
return randomColor;
// The random color will be freshly served
}
var h3 = document.getElementsByTagName("h3");
window.setInterval(function () {
<!-- setting the random color -->
h3[0].style.color = generateRandomColor();
}, 5000);
</script>
</body>
</html>

Related

I have trouble hiding elements in my game if they don't match

I am working on a memory game and I asked a previous question earlier which was answered. I've had this problem and I haven't been able to find a solution with effort. So it's a memory game and when the cards are clicked, they are pushed into an array which can hold two elements at max (you can only click two cards) and then the two elements' frontSrc is checked if they are the same. I set that using an expando property. If so, have them visible and then clear the array so I can do more comparisons. However, it doesn't seem to be working as intended. I'll attach a video below. I've tried using timeout to set the length again, but that didn't work. It works for the first cards, but the other ones after that, it doesn't work.
Here is my code.
<!DOCTYPE html>
<!--
Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
Click nbfs://nbhost/SystemFileSystem/Templates/Other/html.html to edit this template
-->
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.card{
width: 35%;
}
#cards{
display: grid;
grid-template-columns:25% 25% 25% 25%;
row-gap: 25px;
}
</style>
</head>
<body onload="init()">
<section id="cards">
</section>
<script>
var arrCards = [];
var arrShowedCards = [];
//appendElements();
function init(){
createCards();
shuffleCards();
appendElements();
}
function createCards(){
var arrCardNames = ["Mouse","Penguin","Pop","Mouse","Penguin","Pop"];
for(var i = 0; i<6; i++){
var card = document.createElement("IMG");
card.src = "Images/red_back.png";
card.className = "card";
card.frontSrc = "Images/" + arrCardNames[i] + ".png";
card.id = "card" + i;
card.addEventListener("click", showCard);
document.getElementById("cards").appendChild(card);
arrCards.push(card);
}
}
function shuffleCards(){
for (let i = arrCards.length-1; i > 0; i--)
{
const j = Math.floor(Math.random() * (i + 1));
const temp = arrCards[i];
arrCards[i] = arrCards[j];
arrCards[j] = temp;
}
return arrCards;
}
function appendElements(){
for(var i = 0; i<arrCards.length; i++){
document.getElementById("cards").appendChild(arrCards[i]);
}
}
function showCard(){
var sourceString = "Images/red_back.png";
this.src = this.frontSrc;
arrShowedCards.push(this);
if(arrShowedCards.length === 2){
if(arrShowedCards[0].frontSrc === arrShowedCards[1].frontSrc){
console.log("Match!");
arrShowedCards = [];
}
else{
console.log("No match!");
setTimeout(function(){
arrShowedCards[0].src = sourceString;
arrShowedCards[1].src = sourceString;
}, 1000);
}
}
}
</script>
</body>
</html>
I am not sure how come it doesn't work for it for the other cards.
Here is the video.
https://drive.google.com/file/d/1aRPfLALHvTKjawGaiRgD1d0hWQT3BPDQ/view
If anyone finds a better way to approach this, let me know.
Thanks!
I think when not match, you need to reset arrShowedCards otherwise its length will be greater than 2 forever.
function showCard() {
var sourceString = "Images/red_back.png";
this.src = this.frontSrc;
arrShowedCards.push(this);
if (arrShowedCards.length === 2) {
var a = arrShowedCards[0], b = arrShowedCards[1];
arrShowedCards.length = 0;
if (a.frontSrc === b.frontSrc) {
console.log("Match!");
} else {
console.log("No match!");
setTimeout(function () {
a.src = sourceString;
b.src = sourceString;
}, 1000);
}
}
}

How can I reset time in a simple game?

I've tried make simple clicking game (if time count is higher than 5, the game is over, but you can reset time if you click generated element).
Unfortunately time is still counting. How can I fix this?
Why do I get this error?
Uncaught TypeError: Cannot set property 'textContent' of null
at js.js:8
at js.js:49
(function() {
const startGame = document.querySelector('button')
let time = 0;
let roll = true;
let h2 = document.querySelector('h2')
h2.textContent = time;
const timeFlow = () => {
time++
}
const resetTime = () => {
time = 0;
console.log(time)
}
const rollBall = () => {
if (roll == true) {
let divCreator = document.createElement('div')
document.body.appendChild(divCreator)
divCreator.classList.add('square')
divCreator.style.backgroundColor = 'red'
divCreator.style.top = Math.floor(Math.random() * 99) + '%'
divCreator.style.left = Math.floor(Math.random() * 99) + '%'
divCreator.addEventListener('click', letsPlay)
divCreator.addEventListener('click', resetTime)
setInterval(timeFlow, 1000)
} else if (roll == false) {
roll = true;
}
}
const letsPlay = (e) => {
let start = document.body.removeChild(e.target)
roll = false;
if (time >= 5) {
alert('U lost')
} else {
rollBall()
}
}
startGame.addEventListener('click', rollBall)
})();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<button>Generate</button>
<script src='js.js'></script>
<h2>Time</h2>
</body>
</html>
You can use the load event instead of an IIFE before the elements exist.
Also your div needs dimensions
Also I assume you want the time in the H2?
Also you need position absolute to move the div
Lastly I clear the interval before a new one
window.addEventListener("load", function() {
const startGame = document.querySelector('button')
const h2 = document.querySelector('h2')
let tId;
let time = 0;
let roll = true;
h2.textContent = time;
const timeFlow = () => {
time++
h2.textContent = time;
}
const resetTime = () => {
time = 0;
}
const rollBall = () => {
if (roll == true) {
let divCreator = document.createElement('div')
document.body.appendChild(divCreator)
divCreator.classList.add('square');
divCreator.style.height = '50px'
divCreator.style.width = '50px'
divCreator.style.backgroundColor = 'red'
divCreator.style.position = 'absolute'
divCreator.style.top = Math.floor(Math.random() * 99) + '%'
divCreator.style.left = Math.floor(Math.random() * 99) + '%'
divCreator.addEventListener('click', letsPlay)
divCreator.addEventListener('click', resetTime)
clearInterval(tId); // remove any running interval
tId = setInterval(timeFlow, 1000)
}
roll = !roll;
}
const letsPlay = (e) => {
let start = document.body.removeChild(e.target)
roll = false;
if (time >= 5) {
alert('U lost')
} else {
roll = true; // right?
rollBall()
}
}
startGame.addEventListener('click', rollBall)
})
body {
height: 100%;
background-color: yellow;
}
<button>Generate</button>
<h2>Time</h2>
Your HTML code is in the wrong order: the <h2> element and the <script> element should be switched.
You should change it like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<button>Generate</button>
<h2>Time</h2>
<script src='js.js'></script>
</body>
</html>

How to update a JavaScript generated HTML variable

I created this little background color changer just for fun and to play around with JS for a bit but I'm having a problem I don't really know how to solve.
This is my HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="script.js" defer></script>
<link rel="stylesheet" href="style.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<title>Color picker</title>
</head>
<body>
<div class="container d-flex align-items-center justify-content-center">
<div>
<button id="main_button" class="btn btn-danger">Change color</button>
</div>
</div>
</body>
</html>
and my JS:
const button = document.querySelector("#main_button");
function randomColor(){
let letters = "0123456789ABCDEF";
let color = "#";
for(let i = 0; i < 6; i++){
color += letters[Math.floor(Math.random() * 16)];
}
return color;
};
function changeBackground(){
document.body.style.backgroundColor = randomColor();
};
function createParagraph(){
let color = randomColor();
const div = document.querySelector(".container");
let par = document.createElement("p");
par.innerHTML = "Current color is " + color;
div.appendChild(par);
}
button.addEventListener("click", changeBackground);
button.addEventListener("click", createParagraph);
And this is my problem, every time I click on the button a new paragraph is being generated with the new color code. But I want the button to update the color code in the same paragraph.
on every click you are adding another p tag - instead create a p tag in your html page-
<p id="colorTag"><p>
in your createParagraph function -
instead of let par = document.createElement("p"); do let par = document.getElementById('colorTag') par.innerHTML = "Current color is " + color;
You are actually creating a new <p>-element every time you call createParagraph().
Instead, you can create a tag in your HTML beforehand, and save its reference (which you can get by querying for it using e.g. document.querySelector()) in a variable.
Then, you can change its content by assigning a new value to its .textContent-property.
Here a demonstration:
var pElement = document.querySelector('#p-id');
document.querySelector('button').addEventListener('click', () => {
pElement.textContent = "This is its new text, assigned using the '.textContent'-property!";
});
<button>Change <p>'s content!</button>
<p id="p-id">This is the initial text.</p>
An important note would be, that you are actually not displaying the current color-value. You are calling randomColor() twice: Once in changeBackground(), and once in createParagraph(), while the created color is only used for either assigning <body> a new background-color or being displayed using the <p>-tag.
To display the actually used color, you need to use the same String for both the assignment and the value of <p>'s content. You can do that by one of the following:
Write both use-cases in one function
Use another variable for the color
Use the value of document.body.style.background (or .backgroundColor, depending on what you used). However, this will return the color in a format like rgb(123, 213, 132), which might be unwanted.
I'll show examples for points 1 and 2.
Point 1 could look like this:
const button = document.querySelector('#main_button');
const pElement = document.querySelector('#p_id');
function randomColor(){
let letters = "0123456789ABCDEF";
let color = "#";
for(let i = 0; i < 6; i++){
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function changeAndUpdateColor() {
let color = randomColor();
document.body.style.background = color;
pElement.textContent = 'Current Color is ' + color;
}
button.addEventListener('click', changeAndUpdateColor);
<button id="main_button">Change Color</button>
<p id="p_id"></p>
Point 2 could look like this:
const button = document.querySelector('#main_button');
const pElement = document.querySelector('#p_id');
var color = '';
function randomColor(){
let letters = "0123456789ABCDEF";
let color = "#";
for(let i = 0; i < 6; i++){
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function changeBackground() {
document.body.style.background = color;
}
function updateParagraph() {
pElement.textContent = 'Current Color is ' + color;
}
function getNewColor() {
color = randomColor();
}
button.addEventListener('click', getNewColor);
button.addEventListener('click', changeBackground);
button.addEventListener('click', updateParagraph);
<button id="main_button">Change Color</button>
<p id="p_id"></p>
However, using this many functions and listeners makes the code look clunky. Instead, you should make use of ES6's function expressions or arrow function expressions.
When using a function expression, we can initialize and use the color-variable inside, making a global variable useless.
const button = document.querySelector('#main_button');
const pElement = document.querySelector('#p_id');
function randomColor(){
let letters = "0123456789ABCDEF";
let color = "#";
for(let i = 0; i < 6; i++){
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
button.addEventListener('click', function() {
let color = randomColor();
document.body.style.background = color;
pElement.textContent = 'Current Color is ' + color;
});
<button id="main_button">Change Color</button>
<p id="p_id"></p>
Speaking of global context:
Declaring many variables and/or functions in the global context will pollute the global namespace, and will be accessible to the user e.g. using the browser-console. This is a problem for functions where sensitive data is handled or accessible.
To free up the global namespace, we can place most of our script inside a so called IIFE, an immediately invoked function expression. Adding this would be as simple as placing your code inside one like this:
(function() {
// Your code ...
})();
The brackets around the function expression itself will group it so it can be executed using the calling brackets (), much like placing a number inside brackets will allow us to call a function on it, like this:
(123).toString();
One further note now would be, that function declarations inside blocks (means: when not declared in the global context) are not part of ECMAScript, making this a non-standardized feature. This might be irrelevant to you, since it is supported in most (if not all) modern browsers anyway. However, in these cases, one should use function expressions referenced by a variable, e.g. like this:
(function() {
var aFunction = function() {
// ...
};
aFunction(); // Executed as usual
})();
Note that function expressions are not hoisted, unlike function declarations, meaning they need to come before their usage in the code.
Accessing characters of a String like accessing entries of an array is another non-standardized feature, again supported in most browsers. The standardized way would be to use String.charAt().
Refactoring your code could look like this:
// Is OK to be globally accessible
function randomColor(){
let letters = "0123456789ABCDEF";
let color = "#";
for(let i = 0; i < 6; i++){
color += letters.charAt(Math.floor(Math.random() * 16));
}
return color;
}
// Should be placed inside an IIFE; the global context is still accessible
(function() {
const button = document.querySelector('#main_button');
const pElement = document.querySelector('#p_id');
button.addEventListener('click', function() {
let color = randomColor();
document.body.style.background = color;
pElement.textContent = 'Current Color is ' + color;
});
})();
<button id="main_button">Change Color</button>
<p id="p_id"></p>
If I understand you correctly, then you want to change the backgroundcolor to the newest paragraph color. Therefor you have to call the changebackground function in the createParagraph function:
function createParagraph(){
let color = randomColor();
const div = document.querySelector(".container");
let par = document.createElement("p");
par.innerHTML = "Current color is " + color;
div.appendChild(par);
changeBackground(color);
}
function changeBackground(newcolor){
document.body.style.backgroundColor = newcolor;
};
button.addEventListener("click", createParagraph);
This would do the job.
You every time create a new paragraph -
HTML File :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="script.js" defer></script>
<link rel="stylesheet" href="style.css" />
<link
href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-
beta1/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-
giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1"
crossorigin="anonymous"
/>
<title>Color picker</title>
</head>
<body>
<div class="container d-flex align-items-center justify-content-center">
<div>
<button id="main_button" class="btn btn-danger">Change color</button>
</div>
<p id="par"></p> <!-- <== You Need this for render every time color -->
</div>
<script src="./script.js"></script>
</body>
</html>
JS File:
const button = document.querySelector("#main_button");
function randomColor() {
let letters = "0123456789ABCDEF";
let color = "#";
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function changeBackground() {
document.body.style.backgroundColor = randomColor();
}
function createParagraph() {
let color = randomColor();
const div = document.querySelector(".container");
let par = document.getElementById("par"); // select paragraph as html file
par.innerHTML = "Current color is " + color; // and render color to paragraph
}
button.addEventListener("click", changeBackground);
button.addEventListener("click", createParagraph);

Call different events when a variable change in JS

I build a small application to switch between random images in an iframe, I would like that after 10 or 20 images the user will get an image or source I want him to get and not a random one, and then return to the loop.
I have a problem with the count and if function, will appreciate any help. Thanks
<body>
<iframe id="img_main" src="https://www.example.com/img_4.jpg" width="600" height="800" frameborder="1" scrolling="no"></iframe>
<br>
<button id="H" type="button" onclick=(newImg(),clickCounter(),changeImg())>images</button>
<div id="result"></div>
<script>
function newImg(){
var myArray = [
"img_1.jpg",
"img_2.jpg",
"img_3.jpg",
"img_4.jpg"
];
var imgNew = "https://example.com/"
var randomItem = myArray[Math.floor(Math.random()*myArray.length)];
document.getElementById("img_main").src = "https://example.com/" + randomItem ;
}
function clickCounter() {
if (typeof(Storage) !== "undefined") {
if (localStorage.clickcount) {
localStorage.clickcount = Number(localStorage.clickcount)+1;
} else {
localStorage.clickcount = 1;
}
function changeImg(){
if (localStorage.clickcount = 10,20) {
document.getElementById("ins_main").src = "https://example.com/pre_defined_img.jpg";
}
}
</script>
</body>
the way I see that...
by simply use of the modulo (finds the remainder after division)
you don't need to use an iframe, img element is enough.
use an IIFE. as closure method
file : "myScript.js"
const imgBox = (function()
{
const refURL = 'https://i.picsum.photos/id/'
, imgName = [ '251/300/500.jpg', '252/300/500.jpg', '253/300/500.jpg', '254/300/500.jpg'
, '255/300/500.jpg', '256/300/500.jpg', '257/300/500.jpg', '258/300/500.jpg'
, '259/300/500.jpg', '260/300/500.jpg', '261/300/500.jpg', '146/300/500.jpg'
, '263/300/500.jpg', '264/300/500.jpg', '265/300/500.jpg', '266/300/500.jpg'
, '267/300/500.jpg', '268/300/500.jpg', '269/300/500.jpg', '270/300/500.jpg'
, '271/300/500.jpg', '272/300/500.jpg', '273/300/500.jpg', '274/300/500.jpg'
]
, imgZero = '250/300/500.jpg'
, imgSiz = imgName.length
, imgMain = document.getElementById('img-main')
;
var imgNum = 0, randomI = 0;
const obj =
{ setNext()
{
if (!(++imgNum % 10)) // each 10 times
{
imgMain.src = refURL + imgZero
}
else
{
randomI = Math.floor(Math.random() * imgSiz)
imgMain.src = refURL + imgName[randomI]
}
return imgNum
}
}
return obj
})()
const btImg = document.getElementById('bt-img')
, imgCount = document.getElementById('img-count')
, banner = document.getElementById('my-banner')
;
btImg.onclick =evt=>
{
let counter = imgBox.setNext()
imgCount.textContent = counter
if (!(counter %50)) // each 50 times..
{
changeBanner()
}
}
// changing banner function...
function changeBanner()
{
//.....
// do what ever you want to change your banner
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
<style>
img#img-main {
width: 300px;
height: 500px;
border: 1px solid grey;
padding: 2px;
}
</style>
</head>
<body>
<img id="img-main" src="https://i.picsum.photos/id/250/300/500.jpg" alt="" >
<p id="img-count">0</p>
<button id="bt-img">Image change</button>
<div id="my-banner">the banner</div>
<script src="myScript.js"></script>
</body>
</html>

How can I use JavaScript to grab a random div?

I'm using JavaScript to create a grid. What I'm trying to do is have a random box that is created change colors when I click on the "Play" button but I cannot seem to get it figured out.
I've tried using various amounts of Math.random(), this might be where my problem is.
const container = document.getElementById('container');
const gameButton = document.createElement('button');
// This is the button I'm trying to use for this.
gameButton.addEventListener('click', function (event) {
let getRandom = document.getElementsByTagName('div');
});
let userInput = prompt('Enter a number between 10-20: ');
if (isNaN(userInput)) {
alert('Numbers only.');
location.reload();
} else if (userInput < 10) {
alert('That\'s less than 10');
location.reload();
} else if (userInput > 20) {
alert('That\'s greater than 20');
location.reload();
} else {
gameButton.textContent = 'Play';
gameButton.style.height = '25px';
gameButton.style.width = '50px';
gameButton.style.borderRadius = '7px';
gameButton.style.marginBottom = '15px';
container.appendChild(gameButton);
}
for (let index = 1; index <= userInput; index++) {
let gameBoard = document.createElement('div');
gameBoard.setAttribute('class', 'game-board');
container.appendChild(gameBoard);
for (let j = 0; j < userInput; j++) {
const square = document.createElement('div');
square.setAttribute('class', 'square');
gameBoard.appendChild(square);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="./style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<title>Document</title>
</head>
<body>
<div id="container">
</div>
<!---<script src="./app.js"></script>--->
</body>
</html>
Expected result is one of the 'divs' changes color when the button is clicked on.
Between your question and your code, it's a little confusing. But just going off what you said, here's a way to choose a random element from a list of elements, provided you give it a class name (feel free to tweak this):
// Function to get a random number, taking in min and max values.
const randomNum = (min, max) => Math.floor(Math.random() * (max - min + 1) + min)
// Function that takes in a class name to select all those elements
// on the page, and returns a random one from the list.
const getRandomElement = className => {
const elements = document.querySelectorAll(`.${className}`)
const num = randomNum(0, elements.length - 1)
return elements[num]
}
You could change the code in your event listener like this:
gameButton.addEventListener('click', function (event) {
let divs = document.getElementsByClassName('game-board');
let random_div = divs[Math.floor(Math.random()*divs.length)];
random_div.style.backgroundColor = 'red';
});
Or if you want only one square to change color, use document.getElementsByClassName('square') instead.
Relevante part o the code. You can make it better checking the elements, the styles, etc. But essentially it is:
gameButton.addEventListener('click', function (event) {
let getRandom = document.getElementsByTagName('div');
var a = Math.random()
let b = a.toString().substr(2, 1)
getRandom[b].style = 'background-color: ' + (parseInt(b) % 2 == 0 ? 'yellow' : 'red')
});
So you use Math.Random to get some random number after the dot(.) and use it to read some index from the collection you get for the getRandom.
Then you just set element style or whatever you want.
The fiddle: https://jsfiddle.net/cm5kyrdj/

Categories