How to change color based on number - javascript

I have just started to learn coding and I have got a problem now.
I have made this black circle witch has number inside and it goes higher every time you click it but I would want now that even numbers would be blue and odd numbers red (1=red, 2=blue, 3=red etc.)
window.onload = function(){
var laskuri = document.getElementById('laskuri');
function kasvata() {
var i =++
laskuri.innerHTML + i;
asetaTaustaVari();
}
function asetaTaustaVari() {
}
laskuri.onclick = kasvata;
}
* {
box-sizing: border-box;
}
main {
text-align: center;
}
#laskuri {
width: 300px;
height: 300px;
background-color: black;
color: white;
margin: 50px auto;
font-size: 200px;
padding: 30px 0px;
border-radius: 50%;
cursor: pointer;
}
<div id=laskuri>0</div>

You can simply do it by putting an if condition and setting color in it
if (val % 2 == 0) {
color = "blue";
} else {
color = "red";
}
or use ternary operator like this
function kasvata() {
var color = '';
var i = ++
document.getElementById('laskuri').innerHTML + i;
var el = document.getElementById('laskuri');
color = el.innerHTML % 2 == 0 ? "blue" : "red";
el.style.color = color;
asetaTaustaVari();
}
function asetaTaustaVari() {
}
laskuri.onclick = kasvata;
<html lang="fi">
<head>
<meta charset="utf-8">
<title>Laskuri</title>
<style>
* {
box-sizing: border-box;
}
main {
text-align: center;
}
#laskuri {
width: 300px;
height: 300px;
background-color: black;
color: white;
margin: 50px auto;
font-size: 200px;
padding: 30px 0px;
border-radius: 50%;
cursor: pointer;
}
</style>
</head>
<body>
<main>
<div id=laskuri>0</div>
</main>
</body>
</html>

You can achieve it by few ways:
Preferred: You can use a special class-name and use it with your element. In JS code you'll just change a class-name depends on the counter:
<style>
.color_red {
color: red;
}
.color_blue{
color: red;
}
</style>
<script>
window.onload = function(){
var laskuri = document.getElementById('laskuri');
var i = 0;
function kasvata() {
i++;
laskuri.innerHTML = i;
asetaTaustaVari();
}
function asetaTaustaVari() {
var clName = i % 2 === 0 ? 'color_blue' : 'color_red';
laskuri.className = clName;
}
laskuri.onclick = kasvata;
}
</script>
Optional: You can change colors of an element with styles changing. The code is almost the same:
function asetaTaustaVari() {
var color = i % 2 === 0 ? 'blue' : 'red';
laskuri.styles.color = color;
}
P.S.: In your code, please, don't write in your own native language (Finnish / Sweden), please, use english words ALWAYS. Not Laskuri - but Counter.

<!-- Javascript -->
function kasvata() {
var i =++
document.getElementById('laskuri').innerHTML + i;
asetaTaustaVari();
}
function asetaTaustaVari() {
var x = Math.floor(Math.random() * 256);
var y = Math.floor(Math.random() * 256);
var z = Math.floor(Math.random() * 256);
var thergb = "rgb(" + x + "," + y + "," + z + ")";
console.log(thergb);
document.getElementById("laskuri").style.color = thergb;
}
laskuri.onclick = kasvata;
<!-- CSS3 -->
* {
box-sizing: border-box;
}
main {
text-align: center;
}
#laskuri {
width: 300px;
height: 300px;
background-color: black;
color: white;
margin: 50px auto;
font-size: 200px;
padding: 30px 0px;
border-radius: 50%;
cursor: pointer;
}
<!-- HTML5 -->
<html lang="fi">
<head>
<meta charset="utf-8">
<title>Laskuri</title>
</head>
<body>
<main>
<div id=laskuri>0</div>
<main>
</body>
</html>

There is no need of any other function. I think it is required only a ternary operator. You have done almost all thing just modify your javascript code like bellow
<script>
function kasvata() {
var i =++
document.getElementById('laskuri').innerHTML + i;
var val = document.getElementById('laskuri').innerHTML;
document.getElementById('laskuri').style.color = val % 2 == 0 ? "blue" : "red";
}
laskuri.onclick = kasvata;
</script>
I hope you can change the minimum to get it done. Here is the example https://jsfiddle.net/doehxkLy/
And if you want to change the color randomly. Please change the line
document.getElementById('laskuri').style.color = val % 2 == 0 ? "blue" : "red";
To
document.getElementById('laskuri').style.color = "#"+((1<<24)*Math.random()|0).toString(16);
Thumbs up.

You could get the number from the html and use parseInt. Then increment the number and add it to the html.
Then using the remainder you can change the color.
For example:
function kasvata() {
var elm = document.getElementById('laskuri');
if (elm && elm.innerHTML !== "") {
var number = parseInt(elm.innerHTML, 10);
number = number + 1;
elm.innerHTML = elm.innerHTML = number.toString();
asetaTaustaVari(number, elm);
}
}
function asetaTaustaVari(i, elm) {
if (i % 2 === 0) {
elm.style.color = "blue";
} else {
elm.style.color = "red";
}
}
laskuri.onclick = kasvata;
* {
box-sizing: border-box;
}
main {
text-align: center;
}
#laskuri {
width: 300px;
height: 300px;
background-color: black;
color: white;
margin: 50px auto;
font-size: 200px;
padding: 30px 0px;
border-radius: 50%;
cursor: pointer;
}
<main>
<div id=laskuri>0</div>
</main>

made you a small codepen for it:
https://codepen.io/anon/pen/jZrELZ
you just need a if to see if innerHTML of laskuri is even or odd. I resolve the rest with adding/removing a class. you could also change the background directly with javascript.

Related

DOM Element Not Rendering on Page Until After JS Transition Completion

The title says it all. To see the issue, copy this code to the following online compiler: https://www.w3schools.com/php/phptryit.asp?filename=tryphp_compiler
<!DOCTYPE HTML>
<html>
<style>
/*MAIN*/
* {
margin: 0;
padding: 0;
user-select: none;
overflow: hidden;
}
body {
background-color: #FF0000;
margin: 0;
padding: 0;
}
/*ELEMENTS*/
div {
width: 100vw;
height: 100vh;
float: left;
margin-left: 0vw;
}
h1 {
font-family: verdana;
font-size: 5vh;
text-transform: uppercase;
}
h1.white {
color: #F4F4F4;
}
</style>
<body>
<div id = "main" style = "width: auto; margin-left: 0vw;">
<div id = "home" class = "container" style = 'background-color: #000000;'>
<h1 class = "white">click arrow to see how the next page doesn't appear until after the transition is complete</h1>
<!--ARROW BUTTON-->
<p id = 'arrowButton' style = 'color: #FFFFFF; position: absolute; height: 10vh; width: auto; margin: 45vh 0 0 75vw; font-size: 3vh;' onMouseDown = 'NextButtonClick();'>--></p>
</div>
<div id = "welcome" class = "container" style = 'background-color: #FFFFFF;'>
<h1 style = 'margin: 47.5vh 0 0 50vw'>welcome to my portfolio</h1>
</div>
</div>
<script>
var mainDiv, welcomeDiv;
var transitionSeconds = 0.5;
var isTransitioning = false;
function NextButtonClick() {
if(!isTransitioning) {
isTransitioning = true;
i = 0;
thisInterval = setInterval(function() {
mainDiv.style.marginLeft = (100 / i) - 101 + "vw";
i++;
if(i == 100) {
clearInterval(thisInterval);
mainDiv.style.marginLeft = "-100vw";
isTransitioning = false;
}
}, transitionSeconds);
}
}
window.onload = function() {
mainDiv = document.getElementById("main");
welcomeDiv = document.getElementById("welcome");
var arrowButton = document.getElementById("arrowButton");
var arrowButtonX, arrowButtonY;
var arrowButtonGlowDistance = 100;
arrowButtonX = arrowButton.getBoundingClientRect().left + arrowButton.getBoundingClientRect().width/2;//center
arrowButtonY = arrowButton.getBoundingClientRect().top + arrowButton.getBoundingClientRect().height/2;//center
document.onmousemove = function(e) {
x = e.clientX; y = e.clientY;
};
};
</script>
</body>
</html>
The background is red on purpose so that you can see how, even though the "welcome" div should be rendered over top the background, it is not being rendered until the very last second after the transition is completed and 100% of the element is on the screen.
I am stumped, and I'm not sure why this is since HTML usually doesn't seem to behave this way. Even when I highlight the element in Inspect Element, the Inspector doesn't show me where the element is on the screen until the final moment when it is rendered.
Any help would be greatly appreciated, and I look forward to hearing your feedback!
The problem here is that your DIVs are placed under each other and while one is moving horizontally, the next div is still underneath of it until first one is completely out of the way (just like Jenga game in reverse).
To solve this, you can try add display: flex, to place them horizontally instead:
var mainDiv, welcomeDiv;
var transitionSeconds = 0.5;
var isTransitioning = false;
function NextButtonClick() {
if (!isTransitioning) {
isTransitioning = true;
i = 0;
thisInterval = setInterval(function() {
mainDiv.style.marginLeft = (100 / i) - 101 + "vw";
i++;
if (i == 100) {
clearInterval(thisInterval);
mainDiv.style.marginLeft = "-100vw";
isTransitioning = false;
}
}, transitionSeconds);
}
}
window.onload = function() {
mainDiv = document.getElementById("main");
welcomeDiv = document.getElementById("welcome");
var arrowButton = document.getElementById("arrowButton");
var arrowButtonX, arrowButtonY;
var arrowButtonGlowDistance = 100;
arrowButtonX = arrowButton.getBoundingClientRect().left + arrowButton.getBoundingClientRect().width / 2; //center
arrowButtonY = arrowButton.getBoundingClientRect().top + arrowButton.getBoundingClientRect().height / 2; //center
document.onmousemove = function(e) {
x = e.clientX;
y = e.clientY;
};
};
* {
margin: 0;
padding: 0;
user-select: none;
overflow: hidden;
}
body {
background-color: #FF0000;
margin: 0;
padding: 0;
}
/*ELEMENTS*/
div {
width: 100vw;
height: 100vh;
float: left;
margin-left: 0vw;
display: flex; /* added */
}
h1 {
font-family: verdana;
font-size: 5vh;
text-transform: uppercase;
}
h1.white {
color: #F4F4F4;
}
<div id="main" style="width: auto; margin-left: 0vw;">
<div id="home" class="container" style='background-color: #000000;'>
<h1 class="white">click arrow to see how the next page doesn't appear until after the transition is complete</h1>
<!--ARROW BUTTON-->
<p id='arrowButton' style='color: #FFFFFF; position: absolute; height: 10vh; width: auto; margin: 45vh 0 0 75vw; font-size: 3vh;' onMouseDown='NextButtonClick();'>--></p>
</div>
<div id="welcome" class="container" style='background-color: #FFFFFF;'>
<h1 style='margin: 47.5vh 0 0 50vw'>welcome to my portfolio</h1>
</div>
</div>

Pausing javascript timer when scroll off the screen

I have a javascript code timer that I borrowed from the internet. The code basically updates some text every 5 seconds. This text is located in the header of the webpage. When the user scrolls down so the text is no longer visible, the text continues to update. How can I modify this code so when the user scrolls so the text is no longer visible, the javascript timer pauses? Then, when the user scrolls back so the text is visible again, the timer resumes.
Thanks in advance!
<h1 id="title-switcher" value="0">One</h1>
<script>
function Counter(elem, delay) {
var value = parseInt(elem.getAttribute("value"), 10);
var interval;
var titles = [
"One",
"Two",
"Three",
"Four",
"Five"
];
function updateDisplay(value) {
elem.innerHTML = value;
}
function run() {
value += 1;
if (value == titles.length) value = 0;
elem.setAttribute("value", value);
updateDisplay(titles[value]);
}
function start() {
interval = window.setInterval(run, delay);
}
// exports
// This actually creates a function that our counter can call
// you'll see it used below.
//
// The other functions above cannot be accessed from outside
// this function.
this.start = start;
}
var elem = document.getElementById("title-switcher");
counter = new Counter(elem, 5000);
counter.start();
</script>
I found this code at this site: https://www.javascripttutorial.net/dom/css/check-if-an-element-is-visible-in-the-viewport/.
(Only works if you click full page).
function isInViewport(el) {
const rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
}
const box = document.querySelector('.box');
const message = document.querySelector('#message');
document.addEventListener('scroll', function () {
const messageText = isInViewport(box) ?
'The box is visible in the viewport' :
'The box is not visible in the viewport';
message.textContent = messageText;
}, {
passive: true
});
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
height: 10000px;
width: 10000px;
background-color: #F0DB4F;
}
#message {
position: fixed;
height: 50px;
width: 100%;
background-color: rgba(255, 255, 255, 0.5);
top: 0;
left: 0;
color: #111;
text-align: center;
display: flex;
justify-content: center;
align-content: center;
align-items: center;
font-weight: bold;
z-index: 1;
}
.box {
position: absolute;
padding: 10px;
background-color: #fff;
border: solid 2px #111;
font-size: 20px;
width: 300px;
height: 250px;
border-radius: 5px;
top: 300px;
left: 100px;
}
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>Check if an element is visible in the viewport</title>
<link rel="stylesheet" href="css/style-viewport.css">
</head>
<body>
<div class="box"></div>
<div id="message">Please scroll to check if the box is visible</div>
<script src="js/app.js"></script>
</body>
</html>
This article explains two ways of finding what you need: https://usefulangle.com/post/113/javascript-detecting-element-visible-during-scroll
You can either calculate the position of the element and compare it to the page height every time there's a scroll event. But this seems to be worse than using the Intersection Observer API.
You can use IntersectionObserver to watch the element is in the viewport and set a flag to keep counting or not.
const elem = document.getElementById("title-switcher");
function Counter(elem, delay) {
var value = parseInt(elem.getAttribute("value"), 10);
var interval;
let keepCounting = true;
var titles = [
"One",
"Two",
"Three",
"Four",
"Five"
];
function updateDisplay(value) {
elem.innerHTML = value;
}
function run() {
if (!keepCounting) return;
value += 1;
if (value == titles.length) value = 0;
elem.setAttribute("value", value);
updateDisplay(titles[value]);
}
function start() {
interval = window.setInterval(run, delay);
const obsr = new IntersectionObserver((entry) => {
console.log(entry[0].isIntersecting ? "yes" : "no")
keepCounting = entry[0].isIntersecting;
}, options);
obsr.observe(elem);
}
// exports
// This actually creates a function that our counter can call
// you'll see it used below.
//
// The other functions above cannot be accessed from outside
// this function.
this.start = start;
}
const options = {
root: null,
rootMargin: '0px',
threshold: 0.1
}
counter = new Counter(elem, 1000);
counter.start();
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
height: 10000px;
width: 10000px;
background-color: #F0DB4F;
}
#title-switcher {
position: absolute;
padding: 10px;
background-color: #fff;
border: solid 2px #111;
font-size: 20px;
width: 300px;
height: 250px;
border-radius: 5px;
top: 600px;
left: 100px;
}
<h1 id="title-switcher" value="0">One</h1>

Is there a way to stop my character going off the screen?

I have a game with a character that goes to a random position whenever you click on it. Also, I made it so the game automatically goes into full-screen. However, sometimes, the character goes way off-screen and (because there are no scroll bars in full-screen) you cant get to it. The code is below.
<!doctype html>
<html>
<head>
<link href='https://fonts.googleapis.com/css?family=Alfa Slab One' rel='stylesheet'> <!-- add the font used -->
<script type="text/javascript">
function move() { //move the bird
const height = screen.height; //set the screen params
const width = screen.width;
const box = document.getElementById("bird"); //search for the bird
let randY = Math.floor((Math.random() * height) + 1); //randomise the coords
let randX = Math.floor((Math.random() * width) + 1);
box.style.transform = `translate(${randX}px, ${randY}px)`; //move the bird
addScore(); //add the score
}
</script>
<script type="text/javascript">
function getreqfullscreen(){ //full screen it. I cant really understand how it works
var root = document.documentElement
return root.requestFullscreen || root.webkitRequestFullscreen || root.mozRequestFullScreen || root.msRequestFullscreen
}
function startFullScreen() {
var pagebody = document.getElementById("main");
var globalreqfullscreen = getreqfullscreen();
document.addEventListener('click', function(e){
var target = e.target
globalreqfullscreen.call(pagebody)
}, false)
}
</script>
<script type="text/javascript">
var points = 0;
function addScore() { //add the score
var pointcount = document.getElementById("scoreCount"); //get the score counter
//var points = 45; --used for testing
points = points + 1; //increment the points
pointcount.innerText = "score: " + points;
//pointCounter.removeChild(pointCounter.childNodes[0]); --used for an older prototype
}
/**************************************/
function startCountdown() { //initiate the timer - starts when the <body> loads
startFullScreen(); //make it full screen
var time = 9999999999999999999999; //would be 60, but I made it infinite
setInterval(function() { //decrease every second
var timer = document.getElementById("Timer"); //get the timer
time = time - 1; //decrement the timer
timer.innerText = "time: " + time;
if(time == 0) { //if you finished
var continuE = prompt("Would you like to restart? (type Y for yes and N for no (case sensitive)).");
if(continuE == "Y") {
window.location.reload();
} else {
history.go(-1);
}
}
},1000);
}
</script>
<style>
html {
cursor: crosshair;
background-color: #00b0e6;
user-select: none;
}
#bird {
position: absolute;
background-color: #ffffff;
cursor: crosshair;
transition: all 1s ease-in-out;
}
#bird:hover {
invert: 0 0 12px #ff0000;
}
/*
span {
height:10px;ss
width:200px;
border:5px double red;
color:#ff00ff;
background-color:#00ffff;
}
*/
p {
color: #ff00ff;
background-color: #000000;
border: 5px double red;
height: 60px;
width: 85px;
margin: 10px;
font-family: "Times New Roman";
}
.restartButton {
border-radius: 999px;
background-color: #ff00ff;
color: #00fffff;
border: 10px double blue;
transition: all 1s ease-out;
margin-left: 50%;
margin-right: 50%;
position: relative;
cursor: help;
}
.restartButton:hover {
border-radius: 999px;
background-color: #ffffff;
color: #4500fff;
border: 10px solid red;
}
#scoreCount {
color: #aff823;
position: fixed;
top: 0;
width: 10px;
height: 10px;
}
#Timer {
color: #aff823;
position: fixed;
top: 0;
left: 200px;
width: 10px;
height: 10px;
}
span {
font-family: Alfa Slab One;
}
#main {
background-color: #00b0e6;
}
</style>
</head>
<body onload="startCountdown()" id="body">
<div id="main">
<div id="pointCounter"><span id="scoreCount"></span><span id="Timer"></span></div>
<input type="button" value="RESTART" onclick="window.location.reload();" class="restartButton"/>
<img src="https://art.pixilart.com/81a784782ea5697.png" alt="" height="50px" width="50px" id="bird" onclick="move();">
</div>
<noscript>
YOU DO NOT HAVE JAVASCRIPT ENABLED. PLEASE ENABLE JAVASCRIPT ELSE THIS WEB PAGE WILL NOT WORK.
</noscript>
</body>
</html>
Because of how stack overflow works, it doesn't go into full-screen.
P.S. I have made it infinite time, it's meant to only be 60 seconds.

modifying this beautiful number ticker

Here is a beautiful Number Ticker. the whole day I was wondering and trying to modify the code to make it as I want but no success till now!
if you work with numbers with two or more digits then the code creates separate black squares to hold each digit ( run code snippet to have a look ), but I want only a single square as the container to hold multiple digit numbers. So if we have a two-digit number like 10 the Number Ticker should be something like this:
And the next move should look like :
I don't want those parallel animations that move two digits like this (Only the single animation is required not both):
Here is the code:
let counters = document.getElementsByClassName('number-ticker');
let defaultDigitNode = document.createElement('div');
defaultDigitNode.classList.add('digit');
for (let i = 0; i < 11; i++) {
defaultDigitNode.innerHTML += i + '<br>';
}
[].forEach.call(counters, function(counter) {
let currentValue = 10;
let digits = [];
generateDigits(currentValue.toString().length);
setValue(currentValue);
setTimeout(function() {
setValue(8);
}, 2000);
setTimeout(function() {
setValue(7);
}, 5000);
function setValue(number) {
let s = number.toString().split('').reverse().join('');
let l = s.length;
if (l > digits.length) {
generateDigits(l - digits.length);
}
for (let i = 0; i < digits.length; i++) {
setDigit(i, s[i] || 0);
}
}
function setDigit(digitIndex, number) {
digits[digitIndex].style.marginTop = '-' + number + 'em';
}
function generateDigits(amount) {
for (let i = 0; i < amount; i++) {
let d = defaultDigitNode.cloneNode(true);
counter.appendChild(d);
digits.unshift(d);
}
}
});
:root {
background-color: #555;
color: white;
font-size: 25vh;
font-family: Roboto Light;
}
body,
html {
margin: 0;
height: 100%;
}
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100%;
}
.number-ticker {
overflow: hidden;
height: 1em;
background-color: #333;
box-shadow: 0 0 0.05em black inset;
}
.number-ticker .digit {
float: left;
line-height: 1;
transition: margin-top 1.75s ease;
border-right: 1px solid #555;
padding: 0 0.075em;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Number Ticker</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="number-ticker.css">
</head>
<body>
<div class="container">
<div class="number-ticker" data-value="0"></div>
</div>
<script src="number-ticker.js"></script>
</body>
</html>
Your css has this
.number-ticker .digit {
float: left;
line-height: 1;
transition: margin-top 1.75s ease;
border-right: 1px solid #555;
padding: 0 0.075em;
}
You need to change it to this
.number-ticker .digit {
float: left;
line-height: 1;
transition: margin-top 1.75s ease;
padding: 0 0.075em;
text-align: center;
}
If you remove border-right: 1px solid #555 you will have it look like 1 box.
Also I added text-align: center to center the numbers.
Hope this solves your problem :)
I think the main issue in your code is the digits variable. It creates an array of HTML elements that holds two blocks.
Also, for this line:
let s = number.toString().split('').reverse().join('');
Why do you need to convert number to a string. You can just pass it as is. Once you add to a string using + it will be converted.
I made few changes to your code and commented out the non-relevant part. Please see below:
let counters = document.getElementsByClassName('number-ticker');
let defaultDigitNode = document.createElement('div');
defaultDigitNode.classList.add('digit');
for (let i = 0; i < 11; i++) {
defaultDigitNode.innerHTML += i + '<br>';
}
[].forEach.call(counters, function(counter) {
// let currentValue = 10;
// let digits = [];
let currentValue = counter.getAttribute("data-value");
let digit = null;
generateDigits(currentValue.toString().length);
setValue(currentValue);
setTimeout(function() {
setValue(8);
}, 2000);
setTimeout(function() {
setValue(7);
}, 5000);
setTimeout(function() {
setValue(10);
}, 8000);
function setValue(number) {
// let s = number.toString().split('').reverse().join('');
// let l = s.length;
/*if (l > digits.length) {
generateDigits(l - digits.length);
}*/
/*for (let i = 0; i < digits.length; i++) {
setDigit(i, s[i] || 0);
}*/
digit.style.marginTop = '-' + number + 'em';
}
/*function setDigit(digitIndex, number) {
console.log(number);
digits[digitIndex].style.marginTop = '-' + number + 'em';
}*/
function generateDigits(amount) {
// console.log("generat", amount);
// for (let i = 0; i < amount; i++) {
let d = defaultDigitNode.cloneNode(true);
digit = counter.appendChild(d);
// digits.unshift(d);
// }
}
});
:root {
background-color: #555;
color: white;
font-size: 25vh;
font-family: Roboto Light;
}
body,
html {
margin: 0;
height: 100%;
}
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100%;
}
.number-ticker {
overflow: hidden;
height: 1em;
background-color: #333;
box-shadow: 0 0 0.05em black inset;
}
.number-ticker .digit {
float: left;
line-height: 1;
transition: margin-top 1.75s ease;
border-right: 1px solid #555;
padding: 0 0.075em;
text-align: center;
}
<div class="container">
<div class="number-ticker" data-value="0"></div>
</div>
Your final JS could be like this:
let counters = document.getElementsByClassName('number-ticker');
let defaultDigitNode = document.createElement('div');
defaultDigitNode.classList.add('digit');
for (let i = 0; i < 11; i++) {
defaultDigitNode.innerHTML += i + '<br>';
}
[].forEach.call(counters, function(counter) {
let currentValue = counter.getAttribute("data-value");
let d = defaultDigitNode.cloneNode(true);
let digit = counter.appendChild(d);
setValue(currentValue);
function setValue(number) {
digit.style.marginTop = '-' + number + 'em';
}
});

Onclick change div image along with background color

I have an image as a button inside a div. By default, I am displaying image1 with background green when I click on the div I should change the background colour to blue and change to image2. Right now I am able to only change the colour but not the image. How to change both image and background colour ?
var count = 0;
function setColor(id) {
var property = document.getElementById(id);
if (count == 0) {
property.style.backgroundColor = "blue";
document.getElementById('1').src = '~/Images/Icons/image1.png';
count = 1;
} else {
property.style.backgroundColor = "green";
document.getElementById('1').src = '~/Images/Icons/image2.png';
count=0
}
}
.buttonclass {
margin-left: 30px;
margin-bottom: 2px;
margin-top: 2px;
width: 25px;
height: 25px;
box-sizing: border-box;
vertical-align: middle;
text-align: center;
position: absolute;
z-index: 100000;
border: solid 1px #777;
background-color: green;
padding: 0px;
}
<div class="buttonclass" id="1" onclick="setColor(1);" >
<img id="1" src="~/Images/Icons/image1.png">
</div>
You already have a variable called 'property', you can use that.
Change your JavaScript to:
var count = 0;
function setColor(id) {
var property = document.getElementById(id);
if (count == 0) {
property.style.backgroundColor = "blue";
property.src = '~/Images/Icons/image1.png';
count = 1;
} else {
property.style.backgroundColor = "green";
property.src = '~/Images/Icons/image2.png';
count=0
}
}
Or you can shorten this to:
var count = 0;
const COLORS = [
"blue",
"green"
];
function setColor(id) {
var property = document.getElementById(id);
property.style.backgroundColor = COLORS[count]
property.src = ('~/Images/Icons/image' + count + '.png';
var count = count == 0 ? 1 : 0;
}
Problem is that you have duplicate ids.
As seen here:
An ID should be unique within a page. However, if more than one element with the specified ID exists, the getElementById() method returns the first element in the source code.
You can append something to make them different. Also, i took permission to change status logic.
var initial = true;
function setColor(id) {
var property = document.getElementById(id+"div");
var propertyImg = document.getElementById(id+"img");
if (initial) {
property.style.backgroundColor = "blue";
propertyImg.src = '~/Images/Icons/image1.png';
} else {
property.style.backgroundColor = "green";
propertyImg.src = '~/Images/Icons/image2.png';
}
initial = !initial;
}
.buttonclass {
margin-left: 30px;
margin-bottom: 2px;
margin-top: 2px;
width: 25px;
height: 25px;
box-sizing: border-box;
vertical-align: middle;
text-align: center;
position: absolute;
z-index: 100000;
border: solid 1px #777;
background-color: green;
padding: 0px;
}
<div class="buttonclass" id="1div" onclick="setColor(1);" >
<img id="1img" src="~/Images/Icons/image1.png">
</div>

Categories