JavaScript Background Color Toggle [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I have this simple function that is just simply supposed to toggle the background color of a button from aqua to red and back again. However, when I call this function, all it does is change it to red and I'm not sure why. I have looked at other similar examples on here and I feel like I'm doing it correctly. Would love some help!
<button id = "button1" onclick="myFunction()">This is a button</button>
button {
background-color: Aqua;
}
function myFunction() {
if (document.getElementById("button1").style.backgroundColor === "Aqua"){
document.getElementById("button1").style.backgroundColor = "Red";
document.getElementById("button1").innerHTML = "I'm RED!!";
} else {
document.getElementById("button1").style.backgroundColor = "Aqua";
document.getElementById("button1").innerHTML = "I'm back BABY!!";
}
}

it works like this
if ($("#yourselector").css('background-color')=="rgb(220,
20, 60)") alert("matched");
you need to convert name to red, green, blue components, you might use this tool
http://www.yellowpipe.com/yis/tools/hex-to-rgb/color-converter.php

The simplest wya to do this is to pass this into your onclick() function and use a ternary operator to determine the toggle state.
function myFunction(btn) {
const isRed = btn.style.backgroundColor === "red";
btn.style.backgroundColor = isRed ? "aqua" : "red";
btn.innerHTML = isRed ? "I'm back BABY!!" : "I'm RED!!";
}
button {
background-color: aqua;
}
<button id="button1" onclick="myFunction(this)">This is a button</button>

the first if statement should have lowercase aqua.. like the following
function myFunction() {
if (document.getElementById("button1").style.backgroundColor === "aqua") {
document.getElementById("button1").style.backgroundColor = "red";
document.getElementById("button1").innerHTML = "I'm RED!!";
} else {
document.getElementById("button1").style.backgroundColor = "aqua";
document.getElementById("button1").innerHTML = "I'm back BABY!!";
}
}
I found out by doing
console.log(document.getElementById("button1").style); and in the log you will have the object where you can unfold and find that the css selector is in lowercase,
also make red the same to avoid confusion.
hope it helps

Related

Uncaught ReferenceError: html is not defined [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 days ago.
This post was edited and submitted for review 2 days ago.
Improve this question
I am just using Javascript here, to make a login page that using captcha. But it throw an error when I tried to produce it. It was saying that html is not defined, I already tried to check the code, but still could not figure it out what went wrong here.
here is the Javascript code that I think the problem is:
(function () {
const fonts =['cursive', 'sans-serif', 'serif', 'monospace'];
let captchaValue = "";
function generateCaptcha(){
let value = btoa(Math.random()*100000000);
value = value.substr(0,5+Math.random()*5);
captchaValue= value;
}
function setCaptcha() {
captchaValue.split("").map((char)=> {
const rotate = -20 + Math.trunc(Math.random()*30);
const font = Math.trunc(Math.random()*fonts.length);
return `<span
style="
transform:rotate(${rotate}deg);
font-family: ${fonts[font]};
"
>
${char}
</span>`;
}).join("");
document.querySelector(".login-form .captcha .preview").innerHTML = html;
}
function initCaptcha(){
document.querySelector(".login-form .captcha .captcha-refresh").addEventListener('click', function(){
generateCaptcha();
setCaptcha();
});
generateCaptcha();
setCaptcha();
}
initCaptcha();
})();
Please helping me to solve this problem, since I am a beginner so I really got no idea when I am getting this error.
Your problem seems to be in this line of code:
document.querySelector(".login-form .captcha .preview").innerHTML = html;
you are setting the innerHTML of the ".preview" element to html which you didn't define anywhere in your code.
I'm not sure of what you want to set it to, but this is merely a guess, you can change the setCaptcha to the following:
function setCaptcha() {
let html = captchaValue.split("").map((char)=> {
const rotate = -20 + Math.trunc(Math.random()*30);
const font = Math.trunc(Math.random()*fonts.length);
return `<span
style="
transform:rotate(${rotate}deg);
font-family: ${fonts[font]};
"
>
${char}
</span>`;
}).join("");
document.querySelector(".login-form .captcha .preview").innerHTML = html;
}

A problem in Changeable Themes with JavaScript [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 9 months ago.
Improve this question
I tried to test myself in JavaScript so I decided to make changeable themes website in codepen with JavaScript this is my code:enter image description here
but it didn't work. please help me with it.
While #LoaiMasri was on a good track to solve the issue, there is still great way of improvement. Espacially to make the code shorter and more efficient if you have more themes to add.
First change you should consider over LoaiMasri's solution is to use a switch-statement over listing tons of if/else-statements.
However that will be to complicated for more then just a handfull of themes. The most efficient way is to add the themes through CSS. For that you do LoaiMasri's approach of using the value-attribute on the option tag. However give it a more direct value like theme-1, theme-2...
Then you use the script below:
document.getElementById('Themes').addEventListener('change', function() {
document.body.className = "";
let theme = document.getElementById("Themes").value;
document.body.classList.add(theme);
});
document.body.className = ""; -> This will remove all classes from the body-tag and works as a reset.
let theme = document.getElementById("Themes").value; -> That gets the value from the option-tag.
document.body.classList.add(theme); -> This will add now a class to the body-tag that equals the value of the option-tag.
All you now have to is to add classes to your CSS that equal the value of the option-tag. This will now solve the issue with 5 lines of JS code no matter how many themes you want to add (which is already smaller then LoaiMasri's solution).
document.getElementById('Themes').addEventListener('change', function() {
document.body.className = "";
let theme = document.getElementById("Themes").value;
document.body.classList.add(theme);
});
.theme-1 {
background-color: white;
color: black;
}
.theme-2 {
background-color: black;
color: white;
}
.theme-3 {
background-color: darkgray;
color: white;
}
<select id="Themes">
<option value="theme-1">White</option>
<option value="theme-2">Black</option>
<option value="theme-3">Dark</option>
</select>
document.getElementById("Themes").addEventListener("change", function () {
document.body.style.backgroundColor = this.value;
});
this is a answer but I recommended to add values as a number
like this code
<select id="Themes">
<option value="1">White</option>
<option value="2">Black</option>
<option value="3">Dark</option>
</select>
document.getElementById("Themes").addEventListener("change", function () {
let theme = document.getElementById("Themes").value;
if (theme == 1) {
document.body.style.backgroundColor = "white";
document.body.style.color = "black";
} else if (theme == 2) {
document.body.style.backgroundColor = "black";
document.body.style.color = "white";
} else if (theme == 3) {
document.body.style.backgroundColor = "darkgrey";
document.body.style.color = "white";
}
});

Program doesn't work and I don't know why [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am making a script that is supposed to display a button and a coloured circle on a webpage. When this button is pressed, it is supposed to change the colour of the circle. There are 3 colours which are supposed to be looped through so they should change, in order, every time I press the button.
The issue is, when i run my code, it simply displays the coloured circle I chose when making the tag and doesn't change when I press the button.
Here's my code:
<!doctype html>
<html>
<head>
<title>Traffic Lights</title>
</head>
<body>
<img id="trafficimg" src="green.jpg" alt="Change Now!">
<button type="button" onClick="changelight()"> Change the Lights! </button>
<script>
var assets = ["red.jpg","yellow.jpg","green.jpg"]
var state = 1
var colour = ""
function changelight() {
if state == 1{
var colour = "green";
if state == 2{
var colour = "orange";
if state == 3{
var colour = "red";
}
if colour.includes("green"){
document.getElementById("trafficimg").setAttribute('src', assets[0]);
state=state+1;
if colour.includes("green"){
document.getElementById("trafficimg").setAttribute('src', assets[1]);
state=state+1;
if colour.includes("green"){
document.getElementById("trafficimg").setAttribute('src', assets[2]);
state=state - 2;
}
}
}
</script>
</body>
</html>
I would be helpful to get simple solutions that don't change the code too much if possible, though, any help is much appreciated. Thank you all.
You need to wrap the conditions in parenthesis
if (state == 1) {
// ^ ^
colour = "green";
// no need to redeclare color
}
// missing curly bracket at the end of if statement
Working example with state as index for the image array.
var assets = ["https://dummyimage.com/50x50/F00/000000&text=+", "https://dummyimage.com/50x50/FF0/000000&text=+", "https://dummyimage.com/50x50/0F0/000000&text=+"],
state = 0;
function changelight() {
state++; // increment state
state %= assets.length; // remainder operator for keeping state in range of array
document.getElementById("trafficimg").setAttribute('src', assets[state]);
}
<img id="trafficimg" src="https://dummyimage.com/50x50/F00/000000&text=+" alt="Change Now!"><br>
<button type="button" onClick="changelight()"> Change the Lights! </button>
Hi there are multiple errors (actually numerous) errors in your short snippet. BTW, I think you wanted to make this:
var state = 1;
var colour = "green";
function changelight(state) {
if (state == 1){color = "green";}
if (state == 2){color = "orange";}
if (state == 3){color = "red";}
switch(color){
case 'green': {document.getElementById("para1").style.background = 'green'; break;}
case 'orange': {document.getElementById("para1").style.background = 'orange'; break;}
case 'red':{document.getElementById("para1").style.background = 'red'; break;}
}
}
<p id="para1" style="background:green;width:50px;height:50px;border-radius:50%;"></p>
<button type="button" onClick="changelight(1)"> green</button>
<button type="button" onClick="changelight(2)"> orange</button>
<button type="button" onClick="changelight(3)"> red</button>

How to change image on click [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
So I want to change an image onClick and change it back oClick.
This is my current code, but for some reason it doesn't work. I can't find out what's wrong with it.
var newsrc = "suspects.png";
var newsrc = "questionmark.png";
function changeImage() {
if ( newsrc == "suspects.png" ) {
document.images["img"].src = "/images/suspects.png";
document.images["img"].alt = "suspects";
newsrc = "questionmark.png";
}; else {
document.images["img"].src = "/images/questionmark.png";
document.images["img"].alt = "questionmark";
newsrc = "suspects.png";
};
};
I´m pretty sure it´s good like this... Why doesn´t it work?
Toggle a image only checking the source
function toggle(){
var img=document.getElementById('img');
img.src=img.src=='url1'?'url2':'url1';// needs to be the full url.
}
Regarding you code:
you define newsrc 2 times and so the first one is lost.newsrc is always "questionmark.png"
}; else{
should be
}else{
and
if you have suspects set then you want questionmark if clicked, and not suspects.so invert the if content.
should be
if suspects then questionmark else suspects
you have
if suspects then suspect else questionmark.
DEMO
http://jsfiddle.net/SLkHu/
Remove extra semicolons ; in your code
It should be
function changeImage() {
if ( newsrc == "suspects.png" ) {
document.images["img"].src = "/images/suspects.png";
document.images["img"].alt = "suspects";
newsrc = "questionmark.png";
} else {
document.images["img"].src = "/images/questionmark.png";
document.images["img"].alt = "questionmark";
newsrc = "suspects.png";
}
}

why is this if statement not doing anything? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
Believe me the HTML won't be necessary on this one since the if statement only deals with the cBox variable. What this does is, create or close a div upon clicking a button, i've tested the functions and they work, what's not working however is the way these functions are called, I've logged the outputs but i get neither of them displayed in the console, this means the code is not running through the if statement for some reason.
Also tried with if (cBox == null) and it doesn't work ...
btnPress.onclick = function formConfirm() {
var cBox = document.getElementById('cBox');
console.log(" but cbox is "+cBox);
if(cBox) {
closecBox();
console.log("cbox exists, closing ...");
} else {
opencBox();
console.log("cbox does not exist, creating...");
}
};
I am not sure i understand your question but if your code is like this seems to work fiddle
function closeBox(elem){
elem.parentNode.removeChild(elem);
}
function openBox(el){
var el = document.createElement('div');
el.setAttribute("id", "cBox");
document.body.appendChild(el);
}
var btnPress = document.getElementById('button');
btnPress.onclick = function formConfirm() {
var cBox = document.getElementById('cBox');
if(cBox) {
closeBox(cBox)
console.log("cbox exists, closing ...");
} else {
openBox(cBox);
console.log("cbox does not exist, creating...");
}
};
If i did not understand your question sorry for having done wasting time.
Guys thank you for all the replies, your hints were definitely helpful for solving this problem, i made so many changes that i lost track but this is the working code
var btnPress = document.getElementById('theBtn');
btnPress.onclick = function formConfirm() {
var cBox = document.getElementById('confirmBox');
console.log("cbox is "+cBox);
if(cBox) {
console.log("cbox exists, closing ...");
closecBox();
} else {
opencBox();
console.log("cbox does not exist, creating...");
}
};
function opencBox() {
var cBox = document.createElement('div');
cBox.id = "confirmBox";
document.body.appendChild(cBox);
cBox.style.display="inline";
};
function closecBox() {
var cBox = document.getElementById('confirmBox');
cBox.style.display="none";
document.body.removeChild(cBox);
};
I also used display style to test some other stuff with animations :) once again, thank you so much for all the comments! They really helped me out figuring the solution!

Categories