JavaScript Function working well on Firefox but not Chrome - javascript

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)";
}
}

Related

Back and Forth Buttons to modify an htl template with new strings

I have to write down a code that allows me to change an attribute of an element. I want to do this through buttons. Basically, the forward button has to choose the next element of a javascript array. The backward button, instead, the previous one. I tried something like this with poor results:
<!--Let us suppose that we have a paragraph-->
<p id='par' style='color:green'>Something</p>
<button onclick="forward()">TGo On !</button>
<!-- The backward button will follow a similar logic-->
<script>
function forward() {
const colors = ['color:pink', 'color': green ','
color: blue ','
color: red '];
if (colors.indexOf(document.getElementById('par').getAttribute('style')) < colors.length)
document.getElementById('par').setAttribute('style', colors[colors.indexOf(document.getElementById('par').getAttribute('style')) + 1])
else {}
}
</script>
Thank you in advance
Use the style property instead of the HTML attribute to edit styles via javascript.
function forward() {
const paragraph = document.getElementById('par');
const colors = ['pink', 'green', 'blue', 'red'];
var current_color_index = colors.indexOf(paragraph.style.color);
var new_color_index = current_color_index === colors.length - 1 ? 0 : current_color_index+1;
paragraph.style.color = colors[new_color_index];
}
<p id='par' style='color:green'>Something</p>
<button onclick="forward()">TGo On !</button>

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>

Using document.querySelector('.').style. to change *two* CSS properties of a different div

In follow-up to an earlier question. I have the following script:
document.querySelector('.clickme').addEventListener('click', function() {
this.style.color = '#f00';
this.style.backgroundColor = '#fff';
});
...which means when the div .clickme is clicked/tapped, the script changes .clickme's own color and backgroundColor properties. Now, instead, I need the script to change not .clickme's own properties, but the color and backgroundColor of another element on the page, a div class (let's call it) .zebra. How should the script be modified to achieve that? (The target of the click/tap would still be .clickme.)
You can use document.querySelector('.zebra') inside click event handler
document.querySelector('.clickme').addEventListener('click', function() {
this.style.color = '#f00';
this.style.backgroundColor = '#fff';
document.querySelector('.zebra').style.color = 'blue';
document.querySelector('.zebra').style.backgroundColor = 'grey';
});
document.querySelector('.clickme').addEventListener('click', function() {
this.style.color = '#f00';
this.style.backgroundColor = '#fff';
document.querySelector('.zebra').style.color = 'blue';
document.querySelector('.zebra').style.backgroundColor = 'grey';
});
<div class='clickme'>Click me</div>
<div class='zebra'>Zebra</div>
Locate the other element with document.querySelector(".zebra") and change its color and background color:
document.querySelector('.clickme').addEventListener('click', function() {
let zebra = document.querySelector('.zebra')
zebra.style.color = '#f00';
zebra.style.backgroundColor = '#fff';
});
Hopefully, this helps.

Change Color onClick

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";

How to change the color of two elements using javascript?

I am a newbie at javascript and I want change the color of elem2. But this doesn´t work:
var elem = document.getElementById("test");
var elem2 = document.getElementById("test2");
var color = elem.style.backgroundColor;
elem2.style.backgroundColor = color;
Any ideas? THX
Try this:
var elem = document.getElementById('test');
var elem2 = document.getElementById('test2');
var color = window.getComputedStyle(elem).getPropertyValue('background-color');
elem2.style.backgroundColor = color;
Sample JSFiddle
Basically your code is correct.
If block with id "test" has attribute "style" with backgroundColor, written inline, it should work. It should be something like:
<div id="test" style="background-color: red"> </div>
If you declare background-color it css style your js will not work.
However next one color identification will work in both situations:
var color = window.getComputedStyle(elem).getPropertyValue('background-color');
So try to debug it using web-inspector.
Make sure variable "color" contains needed color - add
console.log(color)
and see result in console.
Also check "elem" and "elem2", maybe you have errors in ids.
change this line
var color = elem.style.backgroundColor;
for this
var color = "red"; // or other you want #333

Categories

Resources