Changing color JavaScript doesn't work - javascript

My problem is: I have three elements on a list, and I have to keep changing the text color when the mouse is hover.
So I am building 3 different functions, because the colors are different.
What I did is:
<script type="text/javascript">
var links = document.getElementsByClassName("menuitems");
function firsthover()
{
links[0].style.color = "rgb(204, 0, 0)"; /*this is for avoiding setInterval delay*/
setInterval(function(){
if(links[0].style.color == "rgb(204, 0, 0)")
{
links[0].style.color = "rgb(235, 153, 153)";
}
if(links[0].style.color == "rgb(235, 153, 153)")
{
links[0].style.color = "rgb(204, 0, 0)";
}
},1150);
}
</script>
The problem is: it changes the color just once.
I tried to use hexadecimal color too, just doesn't work.
Please be patient, I am still a novice.

The problem is a small logical flaw. The color does change, but it changes back right away.
If the first if statement evaluates as true and the color is set to rgb(235, 153, 153) the second if statement happens to be true as well, and gets checked right after the change. The color then changes back to the other rgb value.
Using else if instead of two separate statements fixes this. Alternatively you could place a return in the first if statement to prevent the second from being executed after the successful change.
if(links[0].style.color == "rgb(204, 0, 0)")
{
links[0].style.color = "rgb(235, 153, 153)";
}
else if(links[0].style.color == "rgb(235, 153, 153)")
{
links[0].style.color = "rgb(204, 0, 0)";
}

You can use CSS.
Put the code below inside your <head> tag.
<style type="text/css">
.menuitems {
color: rgb(204, 0, 0);
}
.menuitems:hover {
color: rgb(235, 153, 153);
}
</style>
It works perfectly well.
You can also use different colors for different items by using different classes.
Define a base class for menuitems, that will be the base color of them. Then add a different class for each color you would like to use.
Your CSS:
<style type="text/css">
.menuitems { /* base color */
color: rgb(204, 0, 0);
}
.menuitems:hover { /* base hover color */
color: rgb(235, 153, 153);
}
.menuitem-red:hover {
color: rgb(255, 0, 0) !important;
}
.menuitem-green:hover {
color: rgb(0, 255, 0) !important;
}
.menuitem-blue:hover {
color: rgb(0, 0, 255) !important;
}
</style>
Your HTML:
<ul id="menu">
<li class="menuitem">Menu item base</li>
<li class="menuitem menuitem-red">Menu item red</li>
<li class="menuitem menuitem-green">Menu item green</li>
<li class="menuitem menuitem-blue">Menu item blue</li>
</ul>
The name of classes I used and the colors are for sample purposes. Feel free to use the ones you think that fits better for your design.

Related

Set darkMode across multiple html pages

I have two html pages(index.htm and details.htm). Whenever I enable dark Mode in details.html, it is retained in the index.html without any issues, but when I go to the details page from the index.html page the darkMode gets disabled.
I'm using local storage for enabling and disabling the darkMode.
My javascript code:
let darkMode = localStorage.getItem("darkMode");
const toggleBtn = document.querySelectorAll("#mode");
document.body.classList.add('lightMode');
function enableDarkMode() {
localStorage.setItem('darkMode', 'enabled');
document.body.classList.add('darkMode');
document.body.classList.remove('lightMode');
}
function disableDarkMode() {
localStorage.setItem('darkMode', null)
document.body.classList.remove('darkMode');
document.body.classList.add('lightMode');
}
toggleBtn.forEach(btn => {
if(darkMode === 'enabled') {
enableDarkMode();
}
btn.addEventListener("click", () => {
darkMode = localStorage.getItem('darkMode')
if (darkMode !== 'enabled') {
enableDarkMode()
} else {
disableDarkMode();
}
});
})
css code :
.lightMode {
--background-color: white;
--textColor: black;
--borderColor: black;
--shadowColor: grey;
--card: white;
--span: rgba(0, 0, 0, 0.459);
--footer: rgb(231, 231, 231);
--element: rgba(0, 0, 0, 0.03);
--tagColor: rgb(66, 66, 66);
}
.darkMode {
--background-color: rgb(25, 25, 25);
--textColor: rgba(255, 255, 255, 0.76);
--borderColor: white;
--shadowColor: black;
--card: rgb(39, 39, 39);
--span: rgba(255, 255, 255, 0.459);
--footer: rgb(56, 56, 56);
--element: rgba(49, 49, 49, 0.493);
--tagColor: rgb(255, 255, 255);
}
My css only consists of a few custom variables with the same name for both themes.
A for my html the body doesn't have any classes. classes for the body tag are added through javascript
Is there a way to set the darkMode to be enabled to all pages unless the the user changes it himself everytime he visits the page?
I see no problem in your JS, you may have not put the class name 'darkMode' in your body tag of html. One thing is for sure that problem is not the script, but css or html. Look your code for these two again.

How to read value of style within CSS function

I'm creating several divs in Javascript by inserting something like this
'<div style="background-color:' + bgColor + '</div>'
Now I want to set the color of the text automatically based on the luminosity of the background to black or white.
I see 2 options - all driven from Javascript or in CSS only. I prefer the CSS option, however, don't know how to read the background color for a CSS function, e.g.
#function set-color($color) {
#if (lightness($color) > 40) {
#return #000;
}
#else {
#return #FFF;
}
}
How can I fetch the background color to do something like this
div { color: set-color(???); }
How about mix-blend-mode ?
There are several ideas put forward in the question about how to choose between black and white for text color depending on the background color.
Most have been answered one way or another in comments. Taking the ideas one by one:
Can we use CSS mix-blend-mode - no. There is no one setting for this that ensures text will appear readable on all possible backgrounds.
Can we use CSS (the preferred method) - unfortunately no as the div requiring the text color to depend on background color is created by JS at run time.
Can we use JS - yes and as the div is being created by JS and having its background-color set then it might as well have its color set then too.
The JS string is as given in the question with the addition of a setting for color:
'<div style="background-color:' + bgColor + '; color: ' + textBlackOrWhite(bgColor) + ';"'
Here is a snippet which defines the function. The snippet also lets you choose a background color and it then sets a color which (roughly) depends on the 'brightness' of the background. See the SO questions referenced here for further discussion as human color perception is a difficult topic.
//from https://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb
function textBlackOrWhite(hex) {
// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
hex = hex.replace(shorthandRegex, function(m, r, g, b) {
return r + r + g + g + b + b;
});
let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);//also checks we have a well-formed hex number
//from https://stackoverflow.com/questions/596216 the answer by #FranciPenov which gives an approximation: (R+R+G+G+G+B)/6
let itsbright = function () { return ((2*parseInt(result[1], 16) + 3*parseInt(result[2], 16) + parseInt(result[3], 16))/6)>127; }
return result ? (itsbright()) ? '#000000' : '#ffffff' : '#000000';//falls back onto black if bgColor was not a well-formed 3 or 6 digit hex color
}
<div id="div" style="font-family: monospace; box-sizing: border-box; margin: 0; padding: 40px 0; width: 100px; height: 100px; border-style: solid; border-radius: 50%; background-color: black; color: white;text-align:center;">#ffffff</div>
Click to choose background color: <input id="input" placeholder='#00000' type='color' value='#000000'/>
<button onclick="let d = document.getElementById('div'); let i = document.getElementById('input'); d.innerHTML = i.value; d.style.backgroundColor = i.value; d.style.color = textBlackOrWhite(i.value);">Submit</button>
I want to set the color of the text automatically based on the
luminosity of the background to black or white.
I recognise this is a different approach from what you're asking for, but one CSS-only approach to having universally-readable text, regardless of background-color is to have white text with a black outline (or vice versa).
You can use 4 text-shadows for the outline:
text-shadow: 1px 1px rgb(0, 0, 0), -1px 1px rgb(0, 0, 0), -1px -1px rgb(0, 0, 0), 1px -1px rgb(0, 0, 0);
Working Example
const divs = [...document.getElementsByTagName('div')];
for (div of divs) {
let redValue = Math.floor(Math.random() * 255);
let greenValue = Math.floor(Math.random() * 255);
let blueValue = Math.floor(Math.random() * 255);
div.style.backgroundColor = `rgb(${redValue}, ${greenValue}, ${blueValue})`;
}
div {
float: left;
width: 180px;
height: 40px;
margin: 0 6px 6px 0;
line-height: 40px;
color: rgb(255, 255, 255);
font-size: 32px;
text-align: center;
text-shadow: 1px 1px rgb(0, 0, 0), -1px 1px rgb(0, 0, 0), -1px -1px rgb(0, 0, 0), 1px -1px rgb(0, 0, 0);
background-color: yellow;
}
<div>Sample Text</div>
<div>Sample Text</div>
<div>Sample Text</div>
<div>Sample Text</div>
<div>Sample Text</div>
<div>Sample Text</div>
<div>Sample Text</div>
<div>Sample Text</div>
<div>Sample Text</div>
<div>Sample Text</div>
<div>Sample Text</div>
<div>Sample Text</div>

javascript page load causing page to bump

I have a page that uses Javascript to switch between subpages in the form of divs. The problem is that when I click between the subpages, the entire page frequently gets shoved upward and hides one of my navigation bars. This happens in all browsers.
http://www.victorsheckels.com
The relevant parts of the page are:
<div id="main" class="content" style="position:absolute; top:64px; left:176px; right:32px; bottom:32px;z-index:11;visibility:hidden;overflow-y:auto; overflow-x:hidden">
<div id="book" class="content" style="position:absolute; top:64px; left:176px; right:32px; bottom:32px;z-index:12;visibility:visible;overflow-y:auto; overflow-x:hidden">
<div id="copyright" class="content" style="position:absolute; top:64px; left:176px; right:32px; bottom:32px;z-index:13;visibility:hidden;overflow-y:auto; overflow-x:hidden">
<script>
function getSub() {
var section = location.hash.slice(1);
if (section == 'about') showMain();
if (section == 'library') showBook();
if (section == 'copyright') showCopyright();
}
function showMain() {
hideBook();
hideCopyright();
document.getElementById("main").style.top = "64px";
document.getElementById("main").style.visibility = "visible";
document.getElementById("mainnav").style.background = "rgba( 255, 153, 0, 0.3)";
document.getElementById("mainnav").style.borderBottom = "#FF9900 1px solid";
}
function hideMain() {
document.getElementById("main").style.top = "100%";
document.getElementById("main").style.visibility = "hidden";
document.getElementById("mainnav").style.background = "rgba( 255, 153, 0, 0)";
document.getElementById("mainnav").style.borderBottom = "#009900 1px solid";
}
function showBook() {
hideMain();
hideCopyright();
document.getElementById("book").style.top = "64px";
document.getElementById("book").style.visibility = "visible";
document.getElementById("booknav").style.background = "rgba( 255, 153, 0, 0.3)";
document.getElementById("booknav").style.borderBottom = "#FF9900 1px solid";
}
function hideBook() {
document.getElementById("book").style.top = "100%";
document.getElementById("book").style.visibility = "hidden";
document.getElementById("booknav").style.background = "rgba( 255, 153, 0, 0)";
document.getElementById("booknav").style.borderBottom = "#009900 1px solid";
}
function showCopyright() {
hideMain();
hideBook();
document.getElementById("copyright").style.top = "64px";
document.getElementById("copyright").style.visibility = "visible";
document.getElementById("copyrightnav").style.background = "rgba( 255, 153, 0, 0.3)";
document.getElementById("copyrightnav").style.borderBottom = "#FF9900 1px solid";
}
function hideCopyright() {
document.getElementById("copyright").style.top = "100%";
document.getElementById("copyright").style.visibility = "hidden";
document.getElementById("copyrightnav").style.background = "rgba( 255, 153, 0, 0)";
document.getElementById("copyrightnav").style.borderBottom = "#009900 1px solid";
}
function showZ1Preview() { document.getElementById("bookpic").style.backgroundImage = "url('zw1.jpg')"; }
function showD1Preview() { document.getElementById("bookpic").style.backgroundImage = "url('dw1.jpg')"; }
function showD2Preview() { document.getElementById("bookpic").style.backgroundImage = "url('dw2.jpg')"; }
function showD3Preview() { document.getElementById("bookpic").style.backgroundImage = "url('dw3.jpg')"; }
</script>
.content {
padding-bottom : 16px; /* 1/16 */
padding-left : 16px; /* 1/16 */
color : #CCCCCC;
border : #000000 solid 1px;
border-top : #009900 solid 1px;
border-bottom-left-radius : 40px;
background : rgba( 0, 0, 0, 0.3);
transition : all 1s;
}
Remove your href="#copyright" on the link to navigate to the copyright tab. You are jumping because you are not only firing your js, but also trying to move to an absolute positioned object.
EDIT: It's a fix, but the underlying issue is the manner in which you are laying objects out. Absolute positioning is nice at times for floating things, but it should be avoided when creating block level elements.

Javascript - Change colour of div based on current colour

I am trying to change the background colour of a div based on it's current colour, via the click of a button.
For example, if the colour is cyan (#00ffff - it should change to yellow ('ffff00).
If the colour is yellow - it should change to magenta (#ff00ff).
If the colour is magenta - it should revert back to cyan.
I have managed to change the color to yellow from cyan, however I am not sure exactly how to write my if statement (assuming an if statement is the best way?) to change the colours based on the current colour.
function ColorFunction() {
if (light.getItem("backgroundColor") == '#00ffff') {
document.getElementById("light").style.backgroundColor = "#ffff00";
}
else
if (light.getItem("backgroundColor") == '#ffff00') {
document.getElementById("light").style.backgroundColor = "#ff00ff";
}
else
if (light.getItem("backgroundColor") == '#ff00ff') {
document.getElementById("light").style.backgroundColor = "00ffff";
}
}
.main {
width:250px;
color: #202020;
background-color: #d0d0d0;
}
.light {
width: 50px;
height: 50px;
background-color: #00ffff
}
#burn {
width: 150px;
font-style: italic;
}
#button {
font-style: bold;
width: 150px;
}
<h1>Disco Inferno</h1>
<div class="light" id="light">
div
</div>
<button onClick="ColorFunction()">Burn!</button>
Ok, lets start at the beginning here.
You have an element with the id light but that does not automatically become a variable you can use in javascript. Its easy enough to make it one:
var light = document.getElementById("light");
Then, i'm not even sure where you get getItem from - perhaps it was a guess - but its not a valid method on an HTMLElement
You could do this with light.style.backgroundColor - see the snippet below.
var colors = ["rgb(0, 255, 255)","rgb(255, 255, 0)","rgb(255, 0, 255)"];
function ColorFunction() {
var light = document.getElementById("light");
var curr = light.style.backgroundColor;
var next = colors.indexOf(curr)+1;
light.style.backgroundColor = colors[next%colors.length];
}
<h1>Disco Inferno</h1>
<div class="light" id="light" style="background-color:#00FFFF">
Burn, baby burn!
</div>
<button onClick="ColorFunction()">Burn!</button>
You could use an object for shifting the colors, after assigning directly a color to the div.
function ColorFunction() {
var colors = {
'rgb(0, 255, 255)': 'rgb(255, 255, 0)',
'rgb(255, 255, 0)': 'rgb(255, 0, 255)',
'rgb(255, 0, 255)': 'rgb(0, 255, 255)'
},
element = document.getElementById("light");
element.style.backgroundColor = colors[element.style.backgroundColor];
}
.main { width:250px; color: #202020; background-color: #d0d0d0; }
.light { width: 50px; height: 50px; background-color: #00ffff; }
#burn { width: 150px; font-style: italic; }
#button { font-style: bold; width: 150px; }
<div class="light" id="light" style="background-color: #00ffff;"></div>
<button onClick="ColorFunction()">Burn!</button>
There is no getItem() that is some made up method. Look at the console and you will see that it is an error. To read background color you should be using style.
var color = elementReference.style.backgroundColor
Now you are relying on a bad feature of JavaScript where you define a variable that matches an id of an element and it is magically a reference to that element.You should not do that. You should define the variable yourself.
var elementReference = document.getElementById("light");
Now the kicker, browsers returning different things when you read color values. SOme hex, some rgb. So checking for color is a bad thing to do. What to do? Use CSS classes.
function ColorFunction(){
var elem = document.getElementById("light");
if(elem.classList.contains("red")) {
elem.classList.remove("red");
elem.classList.add("blue");
} else if(elem.classList.contains("blue")) {
elem.classList.remove("blue");
elem.classList.add("green");
} else {
elem.classList.remove("green");
elem.classList.add("red");
}
}
.red { background-color: red;}
.blue {background-color: blue;}
.green {background-color: green;}
<h1>Disco Inferno</h1>
<div class="light red" id="light">
div
</div>
<button onClick="ColorFunction()">Burn!</button>
Now there are other ways to do the if check with add/remove, but that is the basic idea.

Switch between black and white background

Aim: switch background color between black and white by clicking one button.
The following is my code, which does not work.
<html>
<body id="pageBody">
<style>
body {background: #000000; color: #FFFFFF;}
</style>
<p>A sentence.</p>
<button type="button" onclick="changeBG()">Change BG</button>
<script>
function changeBG() {
var bg = document.getElementById("pageBody");
if (bg.style.backgroundColor=="#000000") {
bg.style.backgroundColor="#FFFFFF";
bg.style.color="#000000";
}
else {
bg.style.backgroundColor="#000000";
bg.style.color="#FFFFFF";
}
}
</script>
</body>
</html>
You're comparing against a hex string - the browser will return RGB values
"rgb(0, 0, 0)" for black and "rgb(255, 255, 255)" for white.
This will work:
function changeBG() {
var bg = document.body;
if (bg.style.backgroundColor=="rgb(0, 0, 0)") {
bg.style.backgroundColor="#FFFFFF";
bg.style.color="#000000";
}
else {
bg.style.backgroundColor="#000000";
bg.style.color="#FFFFFF";
}
}
Working demo: http://jsfiddle.net/FTSYF/
Use classes to make the code more reusable, and to avoid dealing with browsers changing color mode:
body {background: #000; color: #fff;}
body.bg {background: #fff; color: #000;}
document.body.classList.toggle('bg');
If you want it to work on old browsers that don't support classList, then use (assuming body doesn't have other classes):
document.body.className = document.body.className ? 'bg' : '';

Categories