Change Color onClick - javascript

I am trying to change the color of an element using .style.color and it isn't going very smoothly. My goal is for it to change red and then blue on clicks. Any recommendations?
var turns = 0;
function dot_01() {
if (turns === 0) {
turns++;
document.getElementById("dot_01").style.color = 'red';
} else if (turns === 1) {
turns--;
document.getElementById("dot_01").style.color = 'blue';
}
}
<div class="dot" id="dot_01" onclick="dot_01()"></div>

You want to use .style.backgroundColor to change the button color. .color is going to change the font color.
<input type="button" value="Click Me" onclick="this.style.backgroundColor = '#000'; this.style.color = '#FFF';" />

If you mean to change the background color try style.backgroundColor like the following way:
document.getElementById("dot_01").style.backgroundColor = 'red';
function dot_01(el) {
if (el.style.backgroundColor === 'red') {
el.style.backgroundColor = 'blue';
}
else el.style.backgroundColor = 'red';
}
<div class="dot" id="dot_01" onclick="dot_01(this)">Container</div>

I'm using this to change styling, it's a very simple JavaScript that changes the display and height properties of the CSS to show / hide a container.
Sorry I haven't changed it to your desired outcome yet but I hope this helps, just modify it to change the color by doing something like:
style="color:red"
https://jsfiddle.net/raydekker/u821a84d/
style="color:red";

Related

Is it possible to store an entire element into a localstorage or else?

I know that i ask the most silliest, but since i'm not familiar and i'm totally a beginner in localstorage i want to see the mechanic of the code how it is working as it should be else . I have created a div box and also two buttons , i want to be able to change the color of that box and store it in a localstorage , so that after refreshing i want end up with the background color of my stylesheet which is Red. So meaning when i change to Blue color after refshing the page to remain that color . Like i sad im pretty much new to localstorage and their use. Anyway thank you for the help that you can give me , i know its again a silly question but im very intresed to that. My javascript code is below as you can see:
var red=document.getElementById("red");
var blue=document.getElementById("blue");
var redColor='red';
var blueColor='blue';
localStorage.setItem('RColor',redColor);
localStorage.setItem('BColor',blueColor);
red.onclick=function red(){
document.getElementById("box").style.backgroundColor=localStorage.getItem('RColor');
};
blue.onclick=function blue(){
document.getElementById("box").style.backgroundColor=localStorage.getItem('BColor');
} ;
Check my comments below. This is one sample usage.
var redColor = 'red';
var blueColor = 'blue';
// When opening, read the Color value from localStorage. If it not set, then use the default color (say red)
document.getElementById("box").style.backgroundColor = localStorage.getItem('Color') || redColor;
var red = document.getElementById("red");
var blue = document.getElementById("blue");
red.onclick = function red() {
// Once user click on red button, Change the box background and update localStorage with Color
localStorage.setItem('Color', redColor);
document.getElementById("box").style.backgroundColor = redColor;
};
blue.onclick = function blue() {
// Once user click on blue button, Change the box background and update localStorage with Color
localStorage.setItem('Color', blueColor);
document.getElementById("box").style.backgroundColor = blueColor;
};
You don't need separate items (RColor and BColor) for the two colors in your localStorage.
Just add a common item called say, boxColor to your localStorage then just toggle its value based on which button is clicked. Now just create a function say, getColor that sets the color of your div based on the boxColor item and run that function when the page loads as well as when any of the two buttons are clicked.
Check the following Code Snippet for a practical example of the above approach.
However, running the following code snippet won't work because StackOverflow doesn't allow you to use localStorage in their code sandbox so you can check this JSFiddle instead to see it in action.
var red = document.getElementById("red");
var blue = document.getElementById("blue");
var box = document.getElementById("box");
var redColor='red';
var blueColor='blue';
function getColor(){
box.style.backgroundColor=localStorage.getItem('boxColor');
}
red.onclick=function red(){
localStorage.setItem('boxColor', redColor);
getColor();
};
blue.onclick=function blue(){
localStorage.setItem('boxColor', blueColor);
getColor();
};
getColor();
#box {
width: 200px;
height: 200px;
margin: 0 auto;
padding: 0;
}
<button id="red">Red</button>
<button id="blue">Blue</button>
<div id="box"></div>
Alternatively, if you don't want to repeat yourself with every colour, just place the colour on the button using a data attribute.
So something like:
// your default color
var defaultColor = "red";
// grab all buttons
var buttons = document.querySelectorAll(".set-color");
// loop over them
for (const button of buttons) {
// apply the btn style (optional)
button.style.color = button.dataset.text || "unset";
button.style.backgroundColor = button.dataset.bg || "unset";
button.style.border = 0;
// attach a click event to the button
button.addEventListener("click", function(e) {
// set element bg color and assign in to localstorage
document.getElementById(
"box"
).style.backgroundColor = localStorage.color = this.dataset.bg;
});
}
// setup the initial state
document.getElementById("box").style.backgroundColor =
localStorage.color || defaultColor;
#box {
display: block;
width: 50px;
height: 50px;
}
<div id="box"></div>
<button class="set-color" data-bg="red" data-text="black">red</button>
<button class="set-color" data-bg="blue" data-text="white">blue</button>
<button class="set-color" data-bg="#000000" data-text="white">#000000</button>
<button class="set-color" data-bg="#ff55aa">#ff55aa</button>

JavaScript in HTML changing background

I have no idea what I am doing. I thought I had everything going well with html, then I had to add some simple javascript.
I am just trying to change the background color when the user clicks a button.
This is what I have so far:
CSS
body {
background-color:grey;
}
Javascript
function changeBackground() {
if (document.body.style.backgroundColor = 'grey')
{
document.body.style.backgroundColor = 'black';
}
else
{
document.body.style.backgroundColor = 'grey';
}
}
Html
<button type="button" onclick="changeBackground()">
Click Me!
</button>
Your if clause is wrong (you are assigning instead of testing the background color):
function changeBackground() {
if (document.body.style.backgroundColor == 'grey'){
document.body.style.backgroundColor = 'black';
} else {
document.body.style.backgroundColor = 'grey';
}
}
Richard, I'll offer an alternative to all of the other answers - and you should consider the following structure in all web front-end that you develop.
HTML is what you display, JS is how it behaves, CSS is how it is styled.
That said, try to avoid styling elements with JS but rather toggle a class and allow CSS to do the work. In your case, you could write:
function changeBackground()
{
$(body).toggleClass('dark');
}
<button type="button" onclick="changeBackground()">
Click Me!
</button>
body
{
background-color: grey;
}
body.dark
{
background-color: black;
}
Here, we're simply toggling a class on and off the body element, the CSS will 'respond' accordingly. We have a nice clear separation of concerns.
You may choose your class name to make more sense than dark, but the idea is your JS doesn't care about colors and details of styling.
Try:
$("button").click(function(){
$("body").css("background-color", "blue");
});
Try the FIDDLE,
The problem is you are using assignment operator = instead of comparison operator == or ===
function changeBackground() {
if (document.body.style.backgroundColor == 'grey') {
document.body.style.backgroundColor = 'red';
} else {
document.body.style.backgroundColor = 'grey';
}
}
Hope this works for you

JavaScript Function working well on Firefox but not Chrome

I have a javascript function that changes color of nav bar on click of button. I used a validator and it returned no errors.I used the validator on both browsers. Here is the part of the code, any suggestions would be greatly appreciated.
<body class ="backgroundTwo">
<h1 class ="centered sansSerif background" >Hello World!</h1>
<div>
<ul class ="center">
<li class ="center"><a id="demo" class ="center" href="about.html" >About This Site</a></li>
<li class ="center"><a id ="demo2" class="center" href="current.html">Current Work</a></li>
<li class ="center"><a id ="demo3" class="center" href="http://www.dallascowboys.com/">Cowboys</a><li>
</ul>
</div>
<h1 class = "centered" > <img src ="image.jpg" alt = "Cowboys" style="width:304px;height:228px;"></h1>
<p class = "centered sansSerifTwo" >This is lrodrig6's CSC412 WebSite Project</p>
<div class ="wrapper">
<button class="button" onclick="colorFunction()">click me</button>
</div>
<script>
function colorFunction(){
var color3 = document.getElementById("demo").style.backgroundColor;
var color2 = document.getElementById("demo2").style.backgroundColor;
var color = document.getElementById("demo3").style.backgroundColor;
if (color === "lightblue" && color2 === "lightblue" && color3 === "lightblue"){
document.getElementById("demo").style.backgroundColor = "white";
document.getElementById("demo2").style.backgroundColor = "white";
document.getElementById("demo3").style.backgroundColor = "white";
} else {
document.getElementById("demo").style.backgroundColor = "lightblue";
document.getElementById("demo2").style.backgroundColor = "lightblue";
document.getElementById("demo3").style.backgroundColor = "lightblue";
}
}
</script>
</body>
</html>
When you set a style attribute of an element (e.g. style.backgroundColor) to "lightblue" you cannot expect to read it back as "lightblue".
For example chrome returns "rgb(173, 216, 230)" instead.
You need to keep a variable to store the current state instead of relying on reading back style attributes.
Reading and writing attributes of style is not like accessing regular members of a Javascript object. Those operations are equivalent to calls to getPropertyValue and setProperty and you have no guarantees that the value you pass when setting will be the same that you get back when retrieving.
For example it's also possible that passing "rgb(1,2,3)" you get back "rgb(1, 2, 3)" (with spaces). This is moreover absolutely evident if you set an attribute to something invalid (you will never read something invalid out of a property).
If you need to store logical state in an HTML element you can use the data attributes that were introduced exactly for this usage.
In your specific case for example I'd write something like:
var color = "lightblue"; // Using a regular variable to store status
function colorFunction(){
// Toggle color
color = (color === "lightblue") ? "white" : "lightblue";
document.getElementById("demo").style.backgroundColor = color;
document.getElementById("demo2").style.backgroundColor = color;
document.getElementById("demo3").style.backgroundColor = color;
}
An alternative to using "style.backgroundColor" would be to use
document.getElementById("demo").setAttribute("style", "background-color: lightblue";
That may yield a more reliable response.
I donot believe this is the right way to do, but you can just replace the lightblue with rgb(173, 216, 230) for a quick solution
like this
function colorFunction(){
var color3 = document.getElementById("demo").style.backgroundColor;
var color2 = document.getElementById("demo2").style.backgroundColor;
console.log(color2);
var color = document.getElementById("demo3").style.backgroundColor;
if (color === "rgb(173, 216, 230)" && color2 === "rgb(173, 216, 230)" && color3 === "rgb(173, 216, 230)"){
document.getElementById("demo").style.backgroundColor = "white";
document.getElementById("demo2").style.backgroundColor = "white";
document.getElementById("demo3").style.backgroundColor = "white";
} else {
document.getElementById("demo").style.backgroundColor = "rgb(173, 216, 230)";
document.getElementById("demo2").style.backgroundColor = "rgb(173, 216, 230)";
document.getElementById("demo3").style.backgroundColor = "rgb(173, 216, 230)";
}
}

Body bgcolor attribute weightage

I have written in css that body will have a blue color but in javascript i have made that body will change color every second, It worked until i added global css. I can't remove the css as it has many rules that i can't unlink. I want a way that all css rules will load but my body color won't get affected.
Screenshot to prove that body bgcolor has been changing by script but not shown:
http://i.gyazo.com/b6a7a0f4c5153c61b38c3552cdcd65fc.gif
Can someone show that how can i include that external global CSS but then also my script can change bgcolor and css will not stop it.
P.S : I am Noob :) !
EDIT:
My Code : http://fiddle.jshell.net/dfywom6a/
Help!
try to use document.body.style.background = color; instead of document.bgColor = color;
That will override global css applied onto body element.
I hope this helps http://jsfiddle.net/ceueqetn/
The bgColor attribute is deprecated. So maybe the CSS rule overrides the color stated in the bgColor attribute.
So, instead of changing bgColor in your JavaScript, consider changing the CSS like this:
var body = document.getElementsByTagName('body')[0];
body.style.setProperty('background-color', 'red');
Here is the updated version of your code.
You need to change your code instead of document.bgColor to this document.body.style.background
Working example here http://fiddle.jshell.net/dfywom6a/42/
function cc() {
window.setInterval("Farbe()", 500);
}
farbe = 1;
function Farbe() {
if (farbe == 1) {
document.body.style.background = "indigo";
farbe = 2;
} else if (farbe == 2) {
document.body.style.background = "red";
farbe = 3;
} else if (farbe == 3) {
document.body.style.background = "orange";
farbe = 4;
} else if (farbe == 4) {
document.body.style.background = "blue";
farbe = 1;
}
}
try to add the !important on your color css.
body {
background: #f00 !important;
}

FAQ dropdown- Text color changed when clicked

I am using a JavaScript dropdown for my FAQ, and what I can't figure out is how to have the color of the question change when clicked, and then change back when clicked again.
Here's the JavaScript:
<script type="text/javascript">
function toggle(Info) {
var CState = document.getElementById(Info);
CState.style.display = (CState.style.display != 'block')
? 'block' : 'none';}
</script>
I know using :action will work just for when the question is clicked, but I'm trying to style it so that each click either turns the color on or off, as that's what happens with the answer dropping down and I'd like both to be coordinated.
If I understand correctly you toggle function shows/hides the answer. Then all you have to do is to get the question container and toggle a css class which contains the text color
For example:
document.getElementById(your question).classList.toggle(your-class);
and in a css file
.your-class {
color: selected color;
}
<style>
.classStyle1 {background-color:white}
.classStyle2 {background-color:green}
</style>
<script type="text/javascript">
function toggle(Info) {
var CState = document.getElementById(Info);
if(CStage.className == "classStyle1"){
CStage.className = classStyle2;
}else{
CStage.className = classStyle1;
}
// or else
// create style attribute for select element and put style='background-color:white' like this
if(CStage.style.backgroundColor == "white"){
CStage.style.backgroundColor = 'green';
}else{
CStage.style.backgroundColor = 'white';
}
</script>
If I understand correctly - try this
CState=document.getElementById("myColor");
CState.onmouseover=function(){this.style.color='red';};
CState.onmouseout=function(){this.style.color='blue';};

Categories

Resources