If statement in javascript not responding to array elements - javascript

6 boxes are declared as array elements.
I assigned an if statement to alert "correct" if the box matching the RGB color of array[2] is clicked and an else statement to alert "wrong" if it does not match the RGB color that is in array element[2].
Everything seems correct but now any colour I click alerts "wrong" which is not meant to be. Because box 3 which is contained in [2] is meant to alert "correct".
Please help me out as I can figure out why it is not displaying "correct" even when I click on the right box which is assigned to [2].
Please how do I go about
this help?
// toggle button-----------------------------------------------------------------------------------------------------------------------------
var click = document.querySelector('button')
function change () {
document.body.classList.toggle('body')
}
click.addEventListener('click', change)
// grid coloursm------------------------------------------------------------------------------------------------------------------------------
var colors = [
'rgb(255,0,0)',
'rgb(255,255,0)',
'rgb(25,0,255)',
'rgb(25,255,203)',
'rgb(250,0,0)',
'rgb(0,255,100)',
]
// picked color****************************************************
var picked = colors[4]
var colourDisplay = document.getElementById('colorDisplay')
colourDisplay.textContent = picked
// select grids****************************************************
var square = document.querySelectorAll('.square')
// add var colors to var square using array************************
for (var i = 0; i < square.length; i++) {
// add initial listeners to square
square[i].style.background = colors[i]
// add clicked listeners to square
square[i].addEventListener('click', function () {
var clickedColor = this.style.background;
if(clickedColor === picked){
alert('correct');
} else {
alert('wrong');
}
});
}
body{
background: #232323;
}
.body{
background-color: rgb(45, 174, 206);
}
.square{
width: 30%;
background: chocolate;
padding-bottom: 30%;
float: left;
margin: 1.66%;
}
#con{
max-width: 660px;
margin: 0 auto;
}
h1{
color: cornsilk;
margin: 0 auto;
}
<!DOCTYPE html>
<!-- this game was developed by alabo -->
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Game project</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="game.css" />
</head>
<body>
<h1> colour <span id="colorDisplay">RGB</span> color game</h1>
<div id="con">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>
<button>click me</button>
</body>
<script src="game.js"></script>
</html>

Well i found the issue in about 30 seconds by adding a console.log in the click event like this:
square[i].addEventListener('click', function () {
var clickedColor = this.style.background;
console.log(clickedColor + ' VS ' + picked);
if(clickedColor === picked){
alert('correct');
} else {
alert('wrong');
}
});
The result when clicking on the fourth box was rgb(250, 0, 0) VS rgb(250,0,0).
So the problem is that the result of this.style.background; is rgb(250, 0, 0) while your array has the color defined as rgb(250,0,0), notice the spacing. So simply fixing your colors array spacing will fix your issue.
And here is the working example:
// toggle button-----------------------------------------------------------------------------------------------------------------------------
var click = document.querySelector('button');
function change () {
document.body.classList.toggle('body');
}
click.addEventListener('click', change);
// grid coloursm------------------------------------------------------------------------------------------------------------------------------
var colors = [
'rgb(255, 0, 0)',
'rgb(255, 255, 0)',
'rgb(25, 0, 255)',
'rgb(25, 255, 203)',
'rgb(250, 0, 0)',
'rgb(0, 255, 100)',
];
// picked color****************************************************
var picked = colors[4];
var colourDisplay = document.getElementById('colorDisplay');
colourDisplay.textContent = picked;
// select grids****************************************************
var square = document.querySelectorAll('.square');
// add var colors to var square using array************************
for (var i = 0; i < square.length; i++) {
// add initial listeners to square
square[i].style.background = colors[i] ;
// add clicked listeners to square
square[i].addEventListener('click', function () {
var clickedColor = this.style.background;
if(clickedColor === picked){
alert('correct');
} else {
alert('wrong');
}
});
}
body{
background: #232323;
}
.body{
background-color: rgb(45, 174, 206);
}
.square{
width: 30%;
background: chocolate;
padding-bottom: 30%;
float: left;
margin: 1.66%;
}
#con{
max-width: 660px;
margin: 0 auto;
}
h1{
color: cornsilk;
margin: 0 auto;
}
<!-- this game was developed by alabo -->
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Game project</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="game.css" />
</head>
<body>
<h1> colour <span id="colorDisplay">RGB</span> color game</h1>
<div id="con">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>
<button>click me</button>
</body>
<script src="game.js"></script>
</html>

The Problem is easy to determine if you use some console.log().
You will see that this.style.background contains more information and not only the background-color.
To solve this problem I've changed it to this.style.backgroundColor but that doesn't completly fix it. You have to remove the spacebars. I did that by using this.style.backgroundColor.split(" ").join("")
// toggle button-----------------------------------------------------------------------------------------------------------------------------
var click = document.querySelector('button')
function change () {
document.body.classList.toggle('body')
}
click.addEventListener('click', change)
// grid coloursm------------------------------------------------------------------------------------------------------------------------------
var colors = [
'rgb(255,0,0)',
'rgb(255,255,0)',
'rgb(25,0,255)',
'rgb(25,255,203)',
'rgb(250,0,0)',
'rgb(0,255,100)',
]
// picked color****************************************************
var picked = colors[4]
var colourDisplay = document.getElementById('colorDisplay')
colourDisplay.textContent = picked
// select grids****************************************************
var square = document.querySelectorAll('.square')
// add var colors to var square using array************************
for (var i = 0; i < square.length; i++) {
// add initial listeners to square
square[i].style.background = colors[i]
// add clicked listeners to square
square[i].addEventListener('click', function () {
var clickedColor = this.style.backgroundColor.split(" ").join("");
if(clickedColor == picked){
alert('correct');
} else {
alert('wrong');
}
});
}
body{
background: #232323;
}
.body{
background-color: rgb(45, 174, 206);
}
.square{
width: 30%;
background: chocolate;
padding-bottom: 30%;
float: left;
margin: 1.66%;
}
#con{
max-width: 660px;
margin: 0 auto;
}
h1{
color: cornsilk;
margin: 0 auto;
}
<!DOCTYPE html>
<!-- this game was developed by alabo -->
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Game project</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="game.css" />
</head>
<body>
<h1> colour <span id="colorDisplay">RGB</span> color game</h1>
<div id="con">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>
<button>click me</button>
</body>
<script src="game.js"></script>
</html>

You have problems in your spacing of rbg(255,0,0). If you console.log(this.style.background) you'll notice that the value is rgb(255, 0, 0) with spaces after the ,. I've also changed one of the values in colors[] from rbg(250, 0, 0) to rbg(255, 0, 0) since I think it's a typo.
// toggle button-----------------------------------------------------------------------------------------------------------------------------
var click = document.querySelector('button')
function change () {
document.body.classList.toggle('body')
}
click.addEventListener('click', change)
// grid coloursm------------------------------------------------------------------------------------------------------------------------------
var colors = [
'rgb(255, 0, 0)',
'rgb(255, 255, 0)',
'rgb(25, 0, 255)',
'rgb(25, 255, 203)',
'rgb(255, 0, 0)',
'rgb(0, 255, 100)',
]
// picked color****************************************************
var picked = colors[4]
var colourDisplay = document.getElementById('colorDisplay')
colourDisplay.textContent = picked
// select grids****************************************************
var square = document.querySelectorAll('.square')
// add var colors to var square using array************************
for (var i = 0; i < square.length; i++) {
// add initial listeners to square
square[i].style.background = colors[i]
// add clicked listeners to square
square[i].addEventListener('click', function () {
var clickedColor = this.style.background;
// console.log("Background: " + this.style.background);
// console.log("Picked: " + picked);
if(clickedColor === picked){
alert('correct');
} else {
alert('wrong');
}
});
}
body{
background: #232323;
}
.body{
background-color: rgb(45, 174, 206);
}
.square{
width: 30%;
background: chocolate;
padding-bottom: 30%;
float: left;
margin: 1.66%;
}
#con{
max-width: 660px;
margin: 0 auto;
}
h1{
color: cornsilk;
margin: 0 auto;
}
<!DOCTYPE html>
<!-- this game was developed by alabo -->
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Game project</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="game.css" />
</head>
<body>
<h1> colour <span id="colorDisplay">RGB</span> color game</h1>
<div id="con">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>
<button>click me</button>
</body>
<script src="game.js"></script>
</html>

The two variables do not have same string. The picked color is a RGB without space between digits and clicked color has a string with space. Javascript compares with each and every character. That's why it is failing.
Clicked color: "rgb(250, 0, 0)"
Picked : "rgb(250,0,0)".
Check this fiddle. I have modified your code.
https://fiddle.jshell.net/c3rmLjgj/

Related

Javascript question about arrays and using image src from it anyone can help? (not random img)

I have created some javascript div, a, img elements.
Making my website easier to read instead of spamming the same stuff over and over again.
My problem right now is -->
I need to use href and src links from my array ("src") and add them to my created imgages and links.
So far i have found only one working way to do it with Math...() but i don't want to show the images in random order i want them to be in the order that i have putted them in the array.
This is my code down below i will be happy if anyone helps me out!
I think this can be solved with forEach but i can't figure it out...
var src = ["https://images.unsplash.com/reserve/bOvf94dPRxWu0u3QsPjF_tree.jpg?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1176&q=80" ,
"https://images.unsplash.com/photo-1458966480358-a0ac42de0a7a?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80"];
(function () {
function createDiv() {
var boardDiv = document.createElement("div");
var link = document.createElement("a");
var img = document.createElement("img");
boardDiv.className = "col-md-6 col-lg-4 item";
boardDiv.appendChild(link);
link.className = "lightbox"
link.appendChild(img);
link.href = src[0];
img.className ="img-fluid image scale-on-hover"
img.src = src[Math.floor(Math.random() * src.length)];
return boardDiv;
}
function createAndModifyDivs() {
var board = document.getElementById("image-builder"),
myDivs = [],
i = 0,
numOfDivs = src.length;
for (i; i < numOfDivs; i += 1) {
myDivs.push(createDiv());
board.appendChild(myDivs[i]);
}
}
createAndModifyDivs();
}());
.gallery-block.grid-gallery{
padding-bottom: 60px;
padding-top: 60px;
}
.gallery-block.grid-gallery .heading{
margin-bottom: 50px;
text-align: center;
}
.gallery-block.grid-gallery .heading h2{
font-weight: bold;
font-size: 1.4rem;
text-transform: uppercase;
}
.gallery-block.grid-gallery a:hover{
opacity: 0.8;
}
.gallery-block.grid-gallery .item img{
box-shadow: 0px 2px 10px rgba(0, 0, 0, 0.15);
transition: 0.4s;
}
.gallery-block.grid-gallery .item{
margin-bottom: 20px;
}
#media (min-width: 576px) {
.gallery-block.grid-gallery .scale-on-hover:hover{
transform: scale(1.05);
box-shadow: 0px 10px 10px rgba(0, 0, 0, 0.15) !important;
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Grid Gallery</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/baguettebox.js/1.10.0/baguetteBox.min.css" />
</head>
<body>
<section class="gallery-block grid-gallery">
<div class="container">
<div class="heading">
<h3>Alexis</h3>
</div>
<div class="row" id="image-builder">
</div>
</div>
</section>
<div id="board">
</div>
</div>
<script src="app.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/baguettebox.js/1.10.0/baguetteBox.min.js"></script>
<script>
baguetteBox.run('.grid-gallery', { animation: 'slideIn' });
</script>
</body>
</html>
You can change your createDiv() function to take in the img src as a parameter and then set it in your for loop. Your code could be cleaned up a bit and I can help with that if you leave a comment but for now I just wanted to answer your initial question.
var src = ["https://images.unsplash.com/reserve/bOvf94dPRxWu0u3QsPjF_tree.jpg?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1176&q=80" ,
"https://images.unsplash.com/reserve/bOvf94dPRxWu0u3QsPjF_tree.jpg?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1176&q=80"];
(function () {
// Take the image link as a parameter called imgSrc
function createDiv(imgSrc) {
var boardDiv = document.createElement("div");
var link = document.createElement("a");
var img = document.createElement("img");
boardDiv.className = "col-md-6 col-lg-4 item";
boardDiv.appendChild(link);
link.className = "lightbox"
img.className ="img-fluid image scale-on-hover"
link.appendChild(img);
// Assuming here you want to link to the image
link.href = imgSrc;
// Set the img src
img.src = imgSrc;
return boardDiv;
}
function createAndModifyDivs(elmId) {
const board = document.getElementById(elmId);
for (const imgSrc of src) {
board.appendChild(createDiv(imgSrc));
}
}
const galleries = ['image-builder', 'image-builder-2'];
for(const gallery of galleries) {
createAndModifyDivs(gallery);
baguetteBox.run(`#${gallery}`);
}
}());
.gallery-block.grid-gallery{
padding-bottom: 60px;
padding-top: 60px;
}
.gallery-block.grid-gallery .heading{
margin-bottom: 50px;
text-align: center;
}
.gallery-block.grid-gallery .heading h2{
font-weight: bold;
font-size: 1.4rem;
text-transform: uppercase;
}
.gallery-block.grid-gallery a:hover{
opacity: 0.8;
}
.gallery-block.grid-gallery .item img{
box-shadow: 0px 2px 10px rgba(0, 0, 0, 0.15);
transition: 0.4s;
}
.gallery-block.grid-gallery .item{
margin-bottom: 20px;
}
#media (min-width: 576px) {
.gallery-block.grid-gallery .scale-on-hover:hover{
transform: scale(1.05);
box-shadow: 0px 10px 10px rgba(0, 0, 0, 0.15) !important;
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Grid Gallery</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/baguettebox.js/1.10.0/baguetteBox.min.css" />
</head>
<body>
<section class="gallery-block grid-gallery">
<div class="container">
<div class="heading">
<h3>Alexis</h3>
</div>
<div class="gallery" id="image-builder">
</div>
</div>
</section>
<section class="gallery-block grid-gallery">
<div class="container">
<div class="heading">
<h3>Other</h3>
</div>
<div class="gallery" id="image-builder-2">
</div>
</div>
</section>
<div id="board">
</div>
</div>
<script src="app.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/baguettebox.js/1.10.0/baguetteBox.min.js"></script>
<script>
</script>
</body>
</html>
You only have to make these two changes, now you will pass the src as a parameter of createDiv() (look for the comments)
In App.js
var src = [
"https://images.unsplash.com/reserve/bOvf94dPRxWu0u3QsPjF_tree.jpg?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1176&q=80",
"https://images.unsplash.com/photo-1458966480358-a0ac42de0a7a?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80",
];
(function () {
//ADD A PARAMETER TO THE FUNCTION HERE
function createDiv(img_src) {
var boardDiv = document.createElement("div");
var link = document.createElement("a");
var img = document.createElement("img");
boardDiv.className = "col-md-6 col-lg-4 item";
boardDiv.appendChild(link);
link.className = "lightbox";
link.appendChild(img);
link.href = src[0];
img.className = "img-fluid image scale-on-hover";
img.src = img_src;
return boardDiv;
}
function createAndModifyDivs() {
var board = document.getElementById("image-builder"),
myDivs = [],
i = 0,
numOfDivs = src.length;
for (i; i < numOfDivs; i += 1) {
//PASS THE SRC OF THE DIRECT IMAGE AS PARAMETER HERE
myDivs.push(createDiv(src[i]));
board.appendChild(myDivs[i]);
}
}
createAndModifyDivs();
})();

Change Text Color Every X Seconds JavaScript

New to javascript. I am writing this website and I want to randomly change the color of the logo periodically whilst the mouse hovers over it. So it goes color1, then waits x milliseconds, then color2 and so on until the mouse is not hovering over it anymore. So far I am only able to change the logo to one randomly chosen color. Furthermore I think the way I am using 'mouseover' and 'mouseout' seems pretty confusing and inefficient, is there a better way to use them?
My code (I've left only the essentials)
!DOCTYPE html>
<html lang="en">
<head>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<link href="styles.css" rel="stylesheet">
<title>My Webpage</title>
<script>
document.addEventListener('DOMContentLoaded', function listen() {
var logo = document.querySelector('.logo-btn');
logo.addEventListener("mouseover", event => setTimeout(changeColor(event), 500));
logo.addEventListener("mouseout", event => resetColor(event));
})
function changeColor (event) {
var colors = ["#ff3300", "#fbfb32", "#99ff33", "orange", "magenta", "#3399ff"]
var color = colors[Math.floor(Math.random() * colors.length)];
var logo = event.target;
logo.style.color = color;
}
function resetColor (event) {
var logo = event.target;
logo.style.color = "black";
}
</script>
</head>
<body>
<header>
<div class="header-logo">
<a href="x">
<button class="logo-btn">Logo</button>
</a>
</div>
</body>
</html>
header {
background-color: #fff;
height: 80px;
position: relative;
}
.header-logo {
font-size: 50px;
position: absolute;
bottom: -15px;
left: 40px;
}
.logo-btn {
background-color: transparent;
border: none;
text-align: bottom;
}
```
Thank you very much!
You had done it pretty much right. All you needed was to use setInterval instead of setTimeout. Also, you need to store the interval in a variable and clear it on mouseout so that the text does not keep changing the color.
let interval;
document.addEventListener('DOMContentLoaded', function listen() {
var logo = document.querySelector('.logo-btn');
logo.addEventListener("mouseover", event => {interval = setInterval(()=>changeColor(event), 500)});
logo.addEventListener("mouseout", event => resetColor(event));
})
function changeColor(event) {
var colors = ["#ff3300", "#fbfb32", "#99ff33", "orange", "magenta", "#3399ff"]
var color = colors[Math.floor(Math.random() * colors.length)];
var logo = event.target;
logo.style.color = color;
}
function resetColor(event) {
var logo = event.target;
logo.style.color = "black";
clearInterval(interval);
}
header {
background-color: #fff;
height: 80px;
position: relative;
}
.header-logo {
font-size: 50px;
position: absolute;
bottom: -15px;
left: 40px;
}
.logo-btn {
background-color: transparent;
border: none;
text-align: bottom;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<link href="styles.css" rel="stylesheet">
<title>My Webpage</title>
</head>
<body>
<header>
<div class="header-logo">
<a href="x">
<button class="logo-btn">Logo</button>
</a>
</div>
</header>
</body>
</html>
A recursive function can be a solution for your problem.
You set mouseOver variable on 1 when mouse is over, and on 0 when mouse is out.
You also call setColor on mouseover and check if mouse is over with mouseOver flag.
Now you call setColor that set a new color every time it's called based on selected variable
var logo = document.querySelector('.logo-btn');
logo.addEventListener("mouseover", event => {setColor(event); mouseOver = 1});
logo.addEventListener("mouseout", event => resetColor(event));
var colors = ["#ff3300", "#fbfb32", "#99ff33", "orange", "magenta", "#3399ff"],
selected = 0,
mouseOver = 0
function setColor(e){
e.target.style.backgroundColor = colors[selected]
if(mouseOver){
setTimeout(function(){
if(colors.length > selected + 1){
selected = 0
}
else{
selected ++
}
setColor(e)
}, 500)
}
}
function resetColor(event){
selected = 0
mouseOver = 0
e.target.style.backgroundColor = colors[selected]
}
It should be like this...
let colors = [1,2,3],
element = document.querySelector('whatever-your-logo'),
colorIndex = 0;
function changeColor(){
//set color
element.style.color = colors[colorIndex];
//change to next color
colorIndex++;
// if it's last color then back to first colorIndex
if(colorIndex >= colors.length-1) colorIndex = 0;
}
//Interval
let priod = 1000; //in ms
let interval = setInterval(changeColor, priod);
//done...

Trying to make a light bulb using HTML & CSS & JS

<!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>3 Circle</title>
<style>
body {background: black;}
.container {display: flex;}
.circle {
width: 500px;
height: 500px;
-webkit-border-radius: 250px;
-moz-border-radius: 250px;
border-radius: 250px;
background: white;
}
.active {
background: yellow !important;
color: red;
}
</style>
</head>
<body>
<section class="container">
<button class="circle circle1">Circle1</button>
<button class="circle circle2">Circle2</button>
<button class="circle circle3">Circle3</button>
</section>
<script>
let cir1 = document.querySelector('.circle1')
let cir2 = document.querySelector('.circle2')
let cir3 = document.querySelector('.circle3')
let allCircle = document.querySelectorAll('.circle');
cir1.addEventListener('onClick', onButton1Click);
cir2.addEventListener('onClick', onButton2Click);
cir3.addEventListener('onClick', onButton3Click);
function onButton1Click() {
if (cir1.classList.contains("active")) {
allCircle.classList.remove('active');
} else {
allCircle.classList.remove('active');
cir1.classList.add('active');
}
}
function onButton2Click() {
if (cir2.classList.contains("active")) {
allCircle.classList.remove('active');
} else {
allCircle.classList.remove('active');
cir2.classList.add('active');
}
}
function onButton3Click() {
if (cir3.classList.contains("active")) {
allCircle.classList.remove('active');
} else {
allCircle.classList.remove('active');
cir3.classList.add('active');
}
}
</script>
</body>
</html>
I am trying to make 3 light bulbs represented by circles using HTML & CSS.
So if I turn one light bulb on using the button, the other ones should turn off using the addeventlistener. I can't find ways to make the light bulb turn yellow. Is there anything I am doing wrong? I looked for typos but I can't find any.
A few small things need to changed here.
The event type to be passed to the addEventListener is 'click' rather than 'onClick'.
The variable allCircle returns a list of dom nodes and not a single dom node. So it is essentially a []. Hence properties and methods that are available on a dom node are not accessible on the variable. What you can rather do is write a loop to access each element of the array and then modify their classes one by one
Might also suggest you to put debugger inside your code to see what is happening line by line. This article by Google should help you on using the Chrome dev tools.
This is my first answer on Stack Overflow.
let cir1 = document.querySelector('.circle1')
let cir2 = document.querySelector('.circle2')
let cir3 = document.querySelector('.circle3')
cir1.addEventListener('click', onButton1Click);
cir2.addEventListener('click', onButton2Click);
cir3.addEventListener('click', onButton3Click);
function removeActive() {
cir1.classList.remove('active');
cir2.classList.remove('active');
cir3.classList.remove('active');
}
function onButton1Click() {
removeActive();
cir1.classList.add('active');
}
function onButton2Click() {
removeActive();
cir2.classList.add('active');
}
function onButton3Click() {
removeActive();
cir3.classList.add('active');
}
body {
background: black;
}
.container {
display: flex;
align-items: flex-start;
}
.circle {
width: 100px;
height: 100px;
max-height: 100px;
-webkit-border-radius: 250px;
-moz-border-radius: 250px;
border-radius: 250px;
background: white;
}
.active {
background: yellow !important;
color: red;
}
<!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>3 Circle</title>
</head>
<body>
<section class="container">
<button class="circle circle1">Circle1</button>
<button class="circle circle2">Circle2</button>
<button class="circle circle3">Circle3</button>
</section>
</body>
</html>
There seem to be two issues here.
When adding an event listener for a click event, it must be called with click that is to be passed as the first parameter to the listener, but you've added onClick
querySelectorAll returns a HTMLCollection. So classList will not be a valid property on it. You might want to loop through the elements from allCircles to remove the class.
I've modified the listener and corrected the classist related fix for the first button here https://jsfiddle.net/gr33nw1zard/y7f5wnda/
should be click event, not 'onClick'.
cir1.addEventListener('click', onButton1Click);
Created one common function for all 3 buttons. onClick event is not available in plain javascript, it's the click that is the correct keyword here. Also, you have to iterate over allCircle's object or use getElementsByClass. This will work for you!
<!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>3 Circle</title>
<style>
body {
background: black;
}
.container {
display: flex;
}
.circle {
width: 500px;
height: 500px;
-webkit-border-radius: 250px;
-moz-border-radius: 250px;
border-radius: 250px;
background: white;
}
.active {
background: yellow !important;
color: red;
}
</style>
</head>
<body>
<section class="container">
<button class="circle circle1">Circle1</button>
<button class="circle circle2">Circle2</button>
<button class="circle circle3">Circle3</button>
</section>
<script>
let cir1 = document.querySelector('.circle1')
let cir2 = document.querySelector('.circle2')
let cir3 = document.querySelector('.circle3')
let allCircle = document.querySelectorAll('.circle');
cir1.addEventListener('click', onButtonClick);
cir2.addEventListener('click', onButtonClick);
cir3.addEventListener('click', onButtonClick);
function onButtonClick(e) {
const cir = e.toElement;
if (cir.classList.contains("active")) {
Object.keys(allCircle).map(circle => allCircle[circle].classList.remove('active'));
} else {
Object.keys(allCircle).map(circle => allCircle[circle].classList.remove('active'));
cir.classList.add('active');
}
}
</script>
</body>
</html>
The onClick should be edited to click

Traffic light using javascript

I want create traffic light controller.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>isiqfor</title>
<link rel="stylesheet" href="style.css">
</head>
<body onload="timer;">
<div id="isiqfor">
<div class="green"></div>
<div class="yellow"></div>
<div class="red"></div>
</div>
<script src="script.js"></script>
</body>
</html>
CSS code:
#isiqfor{
border: 10px solid black;
padding: 10px 3px;
width: 50px;
}
#isiqfor>div{
width:50px;
height: 50px;
border-radius: 50%;
opacity: .3;
}
.green{
background-color: green;
}
.yellow{
background-color: yellow;
}
.red{
background-color: red;
}
And JS file:
function myFun () {
// body...
var green=document.getElementsByClassName("green")[0];
var red=document.getElementsByClassName("red")[0];
var yellow=document.getElementsByClassName("yellow")[0];
green.style.opacity=1;
setTimeout(function () {
/* body... */
green.style.opacity=.3;
red.style.opacity=.3;
yellow.style.opacity=1;
},5000);
setTimeout(function () {
/* body... */
green.style.opacity=.3;
red.style.opacity=1;
yellow.style.opacity=.3;
},7000);
setTimeout(function () {
/* body... */
green.style.opacity=1;
red.style.opacity=.3;
yellow.style.opacity=.3;
},12000);
}
var timer = setInterval(function () {
/* body... */
myFun()
},13000);
But problem is when page loads it must wait 13 second for beginning traffic light.How can solve this problem? I want when page loads green light has switched.
Have you tried calling myFun straight away after your timer is set? See the call to myFun added to the bottom of the following code:
var timer = setInterval(function () {
/* body... */
myFun()
},13000);
myFun();//Call 'myFun' straight away...
I created a simple traffic light system! Try this one.
I used jquery to simplify the attribute selection.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<title>Traffic Lights</title>
</head>
<body>
<p>Demonstrate traffic lights system</p>
<div id="div1" style="width:80px;height:80px;background-color:white;border: 1px solid #000;"></div><br>
<div id="div2" style="width:80px;height:80px;background-color:white;border: 1px solid #000;"></div><br>
<div id="div3" style="width:80px;height:80px;background-color:white;border: 1px solid #000;"></div>
</body>
<script>
$(document).ready(function () {
var state = 0;
setInterval(function () {
// state 0 > STOP
// state 1 > READY
// state default > GO
switch (state) {
case 0:
state = 1;
$('#div3').css({ 'background-color': 'white' });
$('#div1').css({ 'background-color': 'red' });
break;
case 1:
state = 3
$('#div1').css({ 'background-color': 'white' });
$('#div2').css({ 'background-color': 'yellow' });
break;
default:
state = 0;
$('#div2').css({ 'background-color': 'white' });
$('#div3').css({ 'background-color': 'green' });
}
}, 2000);
});
</script>
</html>

Javascript a4 paper size

I am using CkEditor.So I set up a4 size for textarea.
CKEDITOR.editorConfig = function( config ) {
config.height = '842px';
config.width = '595px';
};
HTML:
<textarea name="Editor" class="ckeditor" id="aboutme"></textarea>
Javascript:
var editor = CKEDITOR.instances.aboutme;
var edata = editor.getData();
var replaced_text = edata.replace(/(\[##.+?##\])/g, '<span style="background-color:yellow"><strong>$1</strong></span>');
editor.setData(replaced_text);
My question:
If textarea has 2 a4 paper, I want to add red underline between first and second a4 paper in textarea.
I tried to replace to do this however I don't have any idea about a4 paper for ckeditor in javascript .
I want to put red underline after 842px(a4 paper size)
How can I put red underline after 842px in javascript ?
Any help will be appreciated.
Thank you.
Try this example using ckeditor + sharedspace + fake paper with A4 Size.:
http://jsbin.com/nokalosuwi/edit?html,output
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"
rel="stylesheet">
<link type="text/css"
href="https://cdnjs.cloudflare.com/ajax/libs/pace/1.0.2/themes/blue/pace-theme-loading-bar.css"
rel="stylesheet">
<style>
.body {
background: rgb(204, 204, 204);
}
.maindiv {
/*
the content is hidden by default,
and will be shown only after
completed page load and
finalized ckeditor startup
*/
display: none;
}
.content-section {
margin-bottom: 100px;
}
article {
background: white;
width: 21cm;
height: 29.7cm;
display: block;
margin: 0 auto 0.5cm;
box-shadow: 0 0 0.5cm rgba(0, 0, 0, 0.5);
padding: 30px;
font-size: 11pt;
line-height: 22pt;
}
article form {
height: 100%;
}
#media print {
body, article[size="A4"] {
margin: 0;
box-shadow: 0;
background: transparent;
}
.cke_pagebreak {
display: block;
page-break-before: always;
}
.content-section {
margin-bottom: 0;
padding-top: 0;
}
.no-print {
display: none;
}
}
</style>
</head>
<body class="body">
<div class="maindiv">
<div id="top-bar" class="navbar-fixed-top no-print">
<div id="top-ck-toolbar">
<!-- ckeditor top toolbar is rendered here -->
</div>
</div>
<div id="content-section" class="content-section">
<article>
<form id="myform" method="post">
<textarea id="mytextarea1" data-ckenable="true"></textarea>
<textarea id="mytextarea2" data-ckenable="true"></textarea>
<textarea id="mytextarea3" data-ckenable="true"></textarea>
</form>
</article>
</div>
<div id="bottom-bar" class="navbar-fixed-bottom no-print">
<div id="bottom-ck-toolbar">
<!-- ckeditor bottom toolbar is rendered here -->
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pace/1.0.2/pace.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://cdn.ckeditor.com/4.5.2/full-all/ckeditor.js"></script>
<script>
//get the id's of elements that contains "data-ckenable" attribute
function get_ckenable_element_ids() {
return $("[data-ckenable]").map(function () {
return this.id;
}).get();
}
var ckenable_element_ids_list = get_ckenable_element_ids();
var ckeditor_config = {
extraPlugins: [
"sharedspace",
].join(),
sharedSpaces: {
top: "top-ck-toolbar",
bottom: "bottom-ck-toolbar"
}
};
//start ckeditor
ckenable_element_ids_list.map(function (id_element) {
CKEDITOR.replace(id_element, ckeditor_config);
});
function fix_content_padding() {
var top_menu = $('#top-ck-toolbar');
var content_div = $('#content-section');
var current_top_menu_height = parseInt(top_menu.css('height').replace(/[^-\d\.]/g, ''));
var new_padding_value_to_content = "".concat(current_top_menu_height + 130).concat("px");
content_div.css('padding-top', new_padding_value_to_content);
console.log("fixxxx: ", new_padding_value_to_content);
}
window.addEventListener('resize.fix_content_padding', fix_content_padding, false);
var paceOptions = {
"ajax": false,
"restartOnRequestAfter": false,
"document": false
};
window.paceOptions = paceOptions;
Pace.on('hide', function () {
$(".maindiv").fadeIn("fast");
fix_content_padding();
});
</script>
</body>
</html>
source: https://gist.github.com/luzfcb/bab605975396bccd4aa3

Categories