Change Color onClick in HTML / CSS - javascript

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

Related

JavaScript Toggle class

'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>

Printed hex color code doesn't match with real background color

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>

How can i put it background image on setAttribute method?

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

Event listener not working?

Sorry for so many questions, but I suck at javascript and want to get good at it. I'm trying to make a page change colors when you press a button as another proof of concept for me, but it's not working and I'm not entirely sure why...
<html>
<head>
</head>
<body>
<button Id="BGchange">BUTTON!</button>
<script type="text/javascript">
button.eventlistener(BGchange, BGcolor());
function BGcolor (){
var BG = BG2+1
var BG2 = BG
if(BG==0){
document.body.style.background = white;
}
else
if(BG==1){
document.body.style.background = black;
}
}
</script>
</body>
</html>
k, fixed a little, here's what I have now:
<html>
<head>
</head>
<body>
<button Id="BGchange">BUTTON!</button>
<script type="text/javascript">
BGchange.addEventListener("click", BGcolor);
var BG++
function BGcolor (){
if(BG==0){
backgroundcolor = "white";
}
else
if(BG==1){
backgroundcolor = "black";
}
}
</script>
</body>
</html>
If you're trying to listen for an event click, then you need something like this:
document.getElementById("BGchange").addEventListener("click", BGcolor);
Then, you need to fix some things in this function:
function BGcolor (){
var BG = BG2+1
var BG2 = BG
if(BG==0){
document.body.style.background = white;
} else if (BG==1) {
document.body.style.background = black;
}
}
Because you are trying to reference BG2 before it has been initialized so it is not clear what you want to be doing there.
In order, the things I changed:
Get the DOM element for the button with document.getElementById()
Use addEventListener() which is the standard way of adding event handlers
Change to the click event which is what buttons create when you click on them
Pass just a reference to the event handler as BGcolor without the parens. You were calling it immediately rather than passing a reference to the function that can be called later.
In addition, a bunch of things to fix in your BGcolor() function:
Variables that remember their state from one function call to the next must be declared outside that function.
A color value is a string so you would use "white", not white.
To change just the background color, it's best to use the backgroundColor property.
Here's a working version:
<button Id="BGchange">BUTTON!</button>
<script type="text/javascript">
document.getElementById("BGchange").addEventListener("click", BGcolor);
var curColor = "white";
function BGcolor (){
if (curColor == "white") {
curColor = "black";
} else {
curColor = "white";
}
document.body.style.backgroundColor = curColor;
}
</script>
Working demo: http://jsfiddle.net/jfriend00/Nk2N5/

Button background color toggle

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.

Categories