Pausing javascript timer when scroll off the screen - javascript

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>

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>

How do I add cases to the switch statement for this terminal emulator codepen?

I am editing the script of this codepen: https://codepen.io/rafael-casachi/pen/qLEeJV
to use on my website, but I can’t figure out how to add more cases to the switch statement that will perform the functions I need. Here’s what I would like to add:
case ‘cd’
the user can type ‘cd’ followed by a word, then go to the page of my website with that path name (e.g. user types ‘cd shop’ and it opens a window with the url www.mywebsite.com/shop)
case ‘find’
the user can type ‘find’ followed by a word to search for that keyword on my website (like a search bar; e.g. the user types ‘find pants’ which triggers a search for anything with the keyword ‘pants’ on my website)
Any idea what I should do? Thanks!
<script>
var util = util || {};
util.toArray = function(list) {
return Array.prototype.slice.call(list || [], 0);
};
var Terminal = Terminal || function(cmdLineContainer, outputContainer) {
window.URL = window.URL || window.webkitURL;
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
var cmdLine_ = document.querySelector(cmdLineContainer);
var output_ = document.querySelector(outputContainer);
const CMDS_ = [
'cat', 'clear', 'date', 'echo', 'help', 'uname', 'whoami', 'me'
];
var fs_ = null;
var cwd_ = null;
var history_ = [];
var histpos_ = 0;
var histtemp_ = 0;
window.addEventListener('click', function(e) {
cmdLine_.focus();
}, false);
</script>
<div id="wrapper">
<output></output>
<div id="input-line" class="input-line">
<div class="prompt"></div><div><input class="cmdline" autofocus /></div>
</div>
</div>
}
.ls-files {
height: 45px;
-webkit-column-width: 100px;
-moz-column-width: 100px;
-o-column-width: 100px;
column-width: 100px;
}
<style>
$font-color: #0f8;
$bg-color: #111;
$header-color: #fff;
$selection-color: #FF5E99;
$font-family: "Courier New", monospace;
$font-size: 13px;
::selection {
background: $selection-color;
}
html, body {
width: 100%;
height: 100%;
margin: 0;
}
body {
font-family: $font-family;
color: $header-color;
background: $bg-color;
font-size: $font-size;
}
#wrapper {
padding: .1em 5em 1em 1em;
line-height: 1;
output {
clear: both;
width: 100%;
h3, h2 {
margin: 0;
}
pre {
margin: 0;
}
p {
margin-top: .5em;
margin-bottom: .5em;
}
}
}
.input-line {
display: -webkit-box;
-webkit-box-orient: horizontal;
</style>

Setting width to span using JavsScript not working

I am trying to dynamically change width of a span based on the content of the span, So my app has a lot of span row-wise and the use modify content of the spans. On change of content I am trying to uniform the width of each span to be equal to the maxWidth of all the spans combined.
i.e spanWidths = [ '50px', '34px', '56px', '87px' ]
I need to convert all these spans into -> [ '87px', '87px', '87px', '87px' ]
The box model for the span :
As you can see the width is set to 87px on the span yet, on inspecting it is weirdly 57.98px which is inclusive of the border, padding and content.
The css for the span : (I am using box-sizing: border-box throughout)
.annotation-speaker {
display: inline-block;
font-size: 14px;
line-height: 25px;
background-color: rgb(224, 239, 241, 0.5);
height: 25px;
padding: 0px 5px 6px 5px;
margin-top: 5px;
border-radius: 4px;
font-weight: 500;
letter-spacing: 0.7px;
overflow: hidden;
text-align: center;
}
I am confused as to how should I be calculating the spanWidths array having the widths of all the spans after on modifies the content in the span.
This is what I am currently doing :
const css = getComputedStyle($speakerBox); // $speakerBox is my span
const r = $speakerBox.getBoundingClientRect();
const w = $speakerBox.scrollWidth + parseInt(css.paddingLeft) + parseInt(css.paddingRight);
maxSpeakerTagWidth = Math.max(maxSpeakerTagWidth, w);
Here r.width and $speakerBox.scrollWidth are different too! Am confused as to which one should I even consider!
And to make all span's the same width as maxSpeakerTagWidth :
$speakerBox.style.width = maxSpeakerTagWidth + 'px';
This isn't working though!
I fiddled a bit on JSFiddle (:P), seem to have found myself a solution, but am still not able to see it work on my project, but work's just fine on JSFiddle!
https://jsfiddle.net/a5kurstv/
<html>
<head>
<style>
.spanBox {
font-size: 14px;
line-height: 25px;
background-color: rgb(224, 239, 241, 0.5);
height: 25px;
padding: 0px 5px;
margin-top: 5px;
border-radius: 4px;
font-weight: 500;
letter-spacing: 0.7px;
text-align: center;
display: inline-block;
margin-left: 1em;
box-sizing: content-box;
}
.input {
display: block;
margin-left: 1em;
}
</style>
</head>
<body>
<!-- Just type in the input box press enter -->
<span id="span1" class="spanBox">gg</span>
<span id="span2" class="spanBox">gg</span>
<span id="span3" class="spanBox">gg</span>
<span id="span4" class="spanBox">gg</span>
<span id="span5" class="spanBox">gg</span>
<input onkeypress="change(event)" class="input" />
</body>
<script>
let maxW = -1;
const change = (e) => {
if(e.keyCode === 13) {
const val = e.target.value;
const $span1 = document.getElementById('span1');
$span1.textContent = `${val}`;
calcMax();
}
}
const calcMax = () => {
maxW = -1;
for(let i = 1; i <= 5; i++) {
const $span = document.getElementById(`span${i}`);
if($span.style.width === '') {
const r = $span.getBoundingClientRect();
maxW = Math.max(maxW, r.width);
}
else {
$span.style.width = '1px';
maxW = Math.max(maxW, $span.scrollWidth);
}
}
setTimeout(() => update(), 100);
}
const update = () => {
console.log("MAX ", maxW);
for(let i = 1; i <= 5; i++) {
const $span = document.getElementById(`span${i}`);
$span.style.width = maxW + 'px';
}
}
calcMax();
</script>
<html>

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.

How to change color based on number

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.

Categories