I have been trying to toggle the background-color property of a button onclick but the color only changes once and does not toggle back and forth. Below is the code.
function btnColor(btn, color) {
var property = document.getElementById(btn);
if (property.style.backgroundColor == "rgb(244,113,33)") {
property.style.backgroundColor=color;
}
else {
property.style.backgroundColor = "rgb(244,113,33)";
}
}
<input type="button" id="btnHousing" value="Housing" onclick="toggleLayer('transparent1');btnColor('btnHousing','rgb(255,242,0)');" />
A simple solution (JS, CSS and HTML in order).
You setup a class in CSS, then select the button (yes the JS could have been done in one line) and toggle the class.
var button1 = document.querySelector("button");
button1.addEventListener("click", function() {
document.body.classList.toggle("colorred");
});
.colorred {
background-color: red;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Change color to background</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="main.css" />
</head>
<body>
<button>Click me!</button>
<script src="main.js"></script>
</body>
</html>
The problem you're having is that the background-color of an element is reported differently in browsers, either rgb, rgba (with, or without, spaces) in hex or in HSL...
So the button will likely never satisfy the if condition, meaning it will always go to the else.
With that in mind, I'd suggest using a class-name to keep track of the un/toggled state:
function btnColor(btn, color) {
var property = document.getElementById(btn);
if (property.className !== 'toggled') {
property.style.backgroundColor=color;
property.className = 'toggled'
}
else {
property.style.backgroundColor = "rgb(244,113,33)";
property.className = '';
}
}
JS Fiddle demo.
Of course, if we're using the class of the element, we might as well use CSS to style the element:
function btnColor(btn) {
var property = document.getElementById(btn);
if (property.className !== 'toggled') {
property.className = 'toggled'
}
else {
property.className = '';
}
}
With the CSS:
#btnHousing {
background-color: rgb(255,242,0);
}
#btnHousing.toggled {
background-color: rgb(244,113,33);
}
JS Fiddle demo.
The previous JavaScript could be simplified (using the same CSS) to:
function btnColor(btn) {
var property = document.getElementById(btn);
property.className = 'toggled' == property.className ? '' : 'toggled';
}
JS Fiddle demo.
Related
I want to understand how this works. In the HTML is used the onclick="changeColor(this)" to communicate with the js. But if I change the word this in the HTML the code stops working. Why?
HTML:
<!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">
<link rel="stylesheet" href="styles.css">
<link rel="script" href="script.js">
<title>Tente vocĂȘ</title>
</head>
<body>
<div onclick="changeColor(this)" style="background-color: blue;">
Me aperte para mudar de cor!
</div>
<script src="script.js"></script>
</body>
</html>
JS:
function changeColor(element) {
var currentColor = element.style.backgroundColor;
if (currentColor == "red") {
element.style.backgroundColor = "green";
}
else {
element.style.backgroundColor = "red";
}
}
this is a javascript keyword, that refers to the element (the div) in this case. If you change it, the div won't be passed to the function, therefore you won't be able to access it and change the background-color.
this is a complex topic in JS. the answer of philale would satisfies but if you want to know more about this I suggest reading this article.
gentle-explanation-of-this-in-javascript
this is a reference to the element which is clicked. If you change that, you change what the element argument is in the function.
However, it's worth noting that the approach of using onclick inline event handlers is outdated and no longer good practice. The better approach is to use unobtrusive event handlers, contained in the JS logic directly:
document.querySelectorAll('div').forEach(div => {
div.addEventListener('click', changeColor);
});
function changeColor(event) {
const element = event.target;
var currentColor = element.style.backgroundColor;
if (currentColor == "red") {
element.style.backgroundColor = "green";
} else {
element.style.backgroundColor = "red";
}
}
div {
background-color: blue;
}
<div>
Me aperte para mudar de cor!
</div>
Alternatively to using this it is possible to pass in the event of the click, handy when more information should be passed to the function. Change in HTML: onclick="changeColor(event)"
function changeColor(event) {
let element = event.currentTarget
var currentColor = element.style.backgroundColor;
if (currentColor == "red") {
element.style.backgroundColor = "green";
}
else {
element.style.backgroundColor = "red";
}
}
If you do not want to pass the event, it can be done like this in Javascript:
function changeColor() {
let element = this.changeColor.caller.arguments[0].currentTarget
var currentColor = element.style.backgroundColor;
if (currentColor == "red") {
element.style.backgroundColor = "green";
}
else {
element.style.backgroundColor = "red";
}
}
'use strict'
const switcher = document.querySelector('.btn');
console.log(switcher);
switcher.addEventListener('click', function() {
document.body.classList.toggle('dark-theme');
let className = document.body.className;
if (className == "light-theme") {
this.textContent = "Dark";
}
else {
this.textContent = "Light";
}
});
Not sure how the toggle works. How is when I click the button the background changes back to the light-theme when the script doesn't even specify to change back to light-theme?
It's the document.body.classList.toggle('dark-theme');.
If that class exists, it is removed. If that class doesn't exist, it is added.
Your button changes the HTML from
<body class="light-theme">
to
<body class="light-theme dark-theme">
and back again.
Using CSS rules, if two rulesets with the same specificity are declared, and one is declared below the other, the one below will take precedence if both apply to an element. So
.light-theme {
/* rules */
}
.dark-theme {
/* rules */
}
will mean that if an element has dark-theme and light-theme, dark-theme's rules will override any duplicate styles applied by light-theme.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Theme</title>
</head>
<body class="light-theme">
<div>
<button type="button" class="btn">Dark</button>
</div>
<script type="text/javascript">
'use strict'
const switcher = document.querySelector('.btn');
console.log(switcher);
switcher.addEventListener('click', function() {
document.body.classList.toggle('dark-theme');
document.body.classList.toggle('light-theme');
let className = document.body.className;
if (className == "light-theme") {
this.textContent = "Dark";
}
else {
this.textContent = "Light";
}
});
</script>
</body>
</html>
I have a background image that is in a style tag at the top of my html. And I want to change it when it turns to night time where the user is. So during the day it is imageA and during night time it is imageB.
The reason the css is in the header is because of my file layout and it wouldn't be able to access the image otherwise.
How do I change this global css styling from an external js file? I want to change the background image value. Any help would be great thank you.
let d;
d = new Date();
var now = d.toString().slice(16,18);
console.log(now);
if (now <= 5, now >= 20) {
console.log("it is night time")
//the code to change the image would be here
} else {
console.log("it is daytime")
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Seldom Seen</title>
<link rel="stylesheet" href="css/flip.css" />
<!--the lines below here is the part i want to change-->
<style>
.bg-image{
background-image:url("images/imageA.png");
}
</style>
</head>
Not sure if this is what you are asking for, but you can use this snippet to change the background-image through JavaScript:
document.querySelector(".bg-image").style.backgroundImage = "url(images/imageB)";
I'm not aware of any ways to modify CSS in the header using JavaScript, but here are two approaches that would solve your problem:
Assign one of the background images to an additional class, which overrides the original assignment by CSS specificity.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Seldom Seen</title>
<link rel="stylesheet" href="css/flip.css" />
<!--the lines below here is the part i want to change-->
<style>
.bg-image{
background-image:url("images/imageDay.png");
}
.bg-image.night{
background-image:url("images/imageNight.png");
}
</style>
</head>
const bg = document.querySelector('.bg-image');
let d;
d = new Date();
var now = d.toString().slice(16,18);
console.log(now);
if (now <= 5, now >= 20) {
console.log("it is night time");
bg.classList.add('night');
} else {
console.log("it is daytime");
bg.classList.remove('night');
}
Modify the style attribute of the element inline:
if (now <= 5, now >= 20) {
document.querySelector('.bg-image').style.backgroundImage = url('./images/imageNight.jpg');
}
else {
document.querySelector('.bg-image').style.backgroundImage = url('./images/imageDay.jpg');
}
The purpose of my website is to find a hex color code by hitting a button, while the website's background is randomly changed by itself. However, when the button is clicked, the printed color code does not match with the current background color. how can I fix this?
const infiniteColorChange = setInterval(() => {
setColor()
}, 5000);
function setColor() {
document.body.style.backgroundColor = getRandomColor();
}
function getRandomColor() {
for(let y = 0; y < 16777215; y++) {
const randomNumber = Math.floor(Math.random()*16777215);
return "#" + randomNumber.toString(16);
}
}
function stopColor() {
clearInterval(infiniteColorChange);
document.getElementById("hexcode").innerHTML = getRandomColor(); // printed code does not match with bg
}
<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>What color is it</title>
</head>
<body>
<h1>What color is it ...</h1>
<h2 id="hexcode"></h2>
<div id="center">
<input type="button" onclick="stopColor()" class="button" value="Find A Color Code For Me">
</div> <!-- onclick stop loop -->
</body>
</html>
Why are you generating another random color to show? You're literally never getting the color you've set.
You should have retrieved it from the style attribute (or store it somewhere).
document.getElementById("hexcode").innerHTML = document.body.style.backgroundColor;
This at least shows something like rgb(123, 45, 67) that matches the background color. You may need some extra work if you want the #rrggbb format.
You are calling getRandomColor twice: once for the background and once for the hex code display. They won't match. Instead, use a variable and set it to the result of the function
let randomColor;
const infiniteColorChange = setInterval(() => {
setColor()
}, 5000);
function setColor() {
randomColor = getRandomColor();
document.body.style.backgroundColor = randomColor;
}
function getRandomColor() {
for(let y = 0; y < 16777215; y++) {
const randomNumber = Math.floor(Math.random()*16777215);
return "#" + randomNumber.toString(16);
}
}
function stopColor() {
clearInterval(infiniteColorChange);
document.getElementById("hexcode").innerHTML = randomColor;
}
Your code in the stopColor function invokes the getRandomColor function, which generates a new random color, rather than using the one that was present when the button was clicked.
You can solve this by adding a new variable that always has the current color in it and referencing that variable in the stopColor function. (You could also just access the current document background color, but storing it in a variable is a bit more scalable.)
Also (FYI), don't use .innerHTML if you can avoid it (which is almost always) because it has security and performance implications to it. Since you aren't reading or writing HTML anyway, use .textContent.
let currentColor = null; // Will always hold the current color
const infiniteColorChange = setInterval(() => {
setColor()
}, 5000);
function setColor() {
currentColor = getRandomColor(); // Store the color for use elsewhere
document.body.style.backgroundColor = currentColor;
}
function getRandomColor() {
for(let y = 0; y < 16777215; y++) {
const randomNumber = Math.floor(Math.random()*16777215);
return "#" + randomNumber.toString(16);
}
}
function stopColor() {
clearInterval(infiniteColorChange);
document.getElementById("hexcode").textContent = currentColor; // Access current color
}
<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>What color is it</title>
</head>
<body>
<h1>What color is it ...</h1>
<h2 id="hexcode"></h2>
<div id="center">
<input type="button" onclick="stopColor()" class="button" value="Find A Color Code For Me">
</div> <!-- onclick stop loop -->
</body>
</html>
I'm making a simple program that cuts the circle evenly.
enter image description here
and I want to put it image using 'setAttribute' method.
but, It doesn't work as i thought.
here is my code.
<!DOCTYPE html>
<html lang="kr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{margin:0; padding:0;}
</style>
<script>
function elt(name, attributes){
var node = document.createElement(name);
if( attributes ){
for(var attr in attributes){
if(attributes.hasOwnProperty(attr)){
node.setAttribute(attr,attributes[attr]);
}
}
}
for(var i=2; i<arguments.length; i++){
var child = arguments[i];
if( typeof child == "string" ){
child = document.createTextNode(child);
}
node.appendChild(child);
}
return node;
}
window.onload=()=>{
const IMG_W_COUNT = 50;
const IMG_H_COUNT = 33;
const IMG_SUM = 1650;
for(var i=1,j=0;i<=IMG_SUM;i++,j+=18){
var ImageSaver = elt("div",{
class:"menu item"+i,
width:18+"px",
height:18+"px",
background:"url('paint.jpg')",
backgroundPosition:0+"px"+" "+j+"px"
});
document.body.appendChild(ImageSaver);
}
}
</script>
</head>
<body>
</body>
</html>
The elt function is a function that helps to easily generate an element.
I'd really appreciate your help.
background, height and width aren't attributes (except on a few elements, and there they are mostly deprecated), nor is backgroundPosition.
To set a CSS property value with a function use setProperty on a style declaration.
Make sure you use the CSS property name, which is background-position not backgroundPosition.
element.style.setProperty("name", "value");
You have to set CSS properties.
element.style.width=18+"px";
element.style.height=18+"px";
element.style.background="url('paint.jpg')";
element.style.backgroundPosition="top right";