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';
}
});
Related
So basically this is Day 3 (other days, I pretty much did nothing to complete the game) of making a game from HTML5. So I'm making a moves system right now, and I guess I'm doing well? (mainly because I'm not sure if I provided the user with too many moves...) But the thing about it is that, I'm kind of having ANOTHER styling issue.
As you can see in the image: I've CLEARLY set dimensions up for the headerDisplay class/id, but NO, it goes out of the div's dimensions and even goes on the grid. I'm also aiming for the time and moves text to be stuck right on top of the grid, similarly to how the word bank is stuck to the bottom of the grid.
I was also aiming for a button that says refresh right under the word bank, however no matter what I tried, the button would just be right the score text, which looks like this:
When I am aiming for this:
Code:
<div class="content" id="content">
<div class="headerDisplay" id="headerDisplay">
</div>
<div class="gameArea" id="gameArea">
</div>
<div class="wordBank" id="wordBank">
</div>
<div class="bottomMenu" id="bottomMenu">
</div>
</div>
::before,
::after {
box-sizing: border-box;
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
.content {
display: grid;
grid-template-rows: repeat(3, max-content);
margin-block: 1em;
margin-inline: auto;
width: 512px;
}
.bottomMenu {
font-size: 24px;
text-align: right;
}
.wordBank {
border: 2.5px solid #000;
border-radius: 5px;
display: flex;
font-size: 1.6em;
min-height: 3em;
justify-content: space-between;
padding: 0.25em;
}
.wordBank span:nth-child(even) {
align-self: end;
}
.gameArea {
font-size: 0;
justify-self: center;
max-width: 100%;
}
.cell {
border: 1px solid black;
width: 50px;
font-size: 1rem;
height: 50px;
display: inline-block;
}
.headerDisplay {
width: 100%;
height: 76.8px;
text-align: right;
font-size: 1.6em;
}
let score = 0;
const headerDisplay = document.getElementById("headerDisplay")
const bottomMenu = document.getElementById("bottomMenu");
const wordBank = document.getElementById("wordBank")
const gameArea = document.getElementById("gameArea")
const rows = document.getElementsByClassName("gridRow");
const cells = document.getElementsByClassName("cell");
const words = [ // snippet
"ability",
"able",
"about",
"above",
"abroad",
"absence",
"absent",
"absolute",
"accept",
"accident",
"accord",
"account",
"accuse",
"accustom",
"ache",
"across",
"act"
]
let selectedWords = [];
bottomMenu.innerHTML = "<p>Score: " + score;
bottomMenu.innerHTML += "<button>Refresh"
while (selectedWords.length < 5) {
const selectedWord = words[Math.floor(Math.random() * words.length)];
if (selectedWord.length <= 9) {
wordBank.innerHTML += "<span>" + selectedWord + "</span>"
selectedWords.push(selectedWord);
}
}
let longestWord = selectedWords.reduce((a, b) => a.length < b.length ? b : a, "")
let charCount = longestWord.length
var moves = charCount * 5
headerDisplay.innerHTML += "<p>Time: "
headerDisplay.innerHTML += "<p>Moves: " + moves
function makeRows(rowNum) {
for (let r = 0; r < rowNum; r++) {
let row = document.createElement("div");
gameArea.appendChild(row).className = "gridRow";
}
}
function makeColumns(cellNum) {
for (let i = 0; i < rows.length; i++) {
for (let j = 0; j < cellNum; j++) {
let newCell = document.createElement("div");
rows[j].appendChild(newCell).className = "cell";
}
}
}
function defaultGrid() {
makeRows(charCount);
makeColumns(charCount);
}
defaultGrid();
To fix header you need to set its height to fit content, so it will be over your grid even if you change it later:
.headerDisplay {
width: 100%;
height: content-fit; /* previous: 76.8px */
text-align: right;
font-size: 1.6em;
}
And to fix bottom menu you need to add flexbox:
.bottomMenu {
font-size: 24px;
text-align: right;
display: flex; /* new */
flex-direction: row-reverse; /* new */
justify-content: space-between; /* new */
align-items: center; /* new */
}
For the button, you could try this:
button {
position: relative;
right: 400px;
bottom: 50px;
transform: scale(2,2)
}
I am making a typing program. Each letter is in its own div, which is broken into words.
For example, the word other would be written as:
<div class="word">
<div class="letter" id="l184"></div>
<div class="letter" id="l185">o</div>
<div class="letter" id="l186">t</div>
<div class="letter" id="l187">h</div>
<div class="letter" id="l188">e</div>
<div class="letter" id="l189">r</div>
</div>
The letter with the cursor before it also has the class cursor.
.cursor:before {
position: absolute;
width: 2px;
height: 30px;
background: var(--accent);
content: ' ';
}
Sometimes, when typing the first word of a line, the completed part of the word, which has the cursor after it, is bumped up to the line before it. This does not happen when the :before has no content. Please help me figure out why something with position: absolute is moving elements around. Thank you!
EDIT: Snippet
EDIT 2: The glitch only works with a certain combination of words, so if you cannot reproduce the glitch, please try again.
let dict = ['test', 'stack', 'overflow'];
let index = 0, words, wrong = 0, last;
let running;
let sec = 0, min = 0;
const text = document.querySelector('#text');
const st = document.querySelector('#sec');
const mt = document.querySelector('#min');
function genTest() {
words = "";
for (let i = 0; i < 100; i++) {
words += dict[randomRange(0, 2)];
if (i !== 99) words += " ";
}
let html = `<div class='word'>`;
let i = 0;
words.split('').forEach(l => {
if (l === ' ') html += `</div><div class="word">`;
if (i === 0) html += `<div class="letter curs-fade" id='l${i}'>${l}</div>`;
else html += `<div class="letter" id='l${i}'>${l}</div>`;
i++;
});
last = i;
html += '</div>'
text.innerHTML = html;
}
function initTest() {
running = false;
genTest();
st.classList = "";
mt.classList = "";
l(0).classList.add('cursor');
}
function start() {
running = true;
st.classList.add('txt-active');
setInterval(() => {
sec++;
if (sec >= 60) {
sec %= 60;
min++;
if (min === 1) {
mt.classList.add('txt-active');
}
}
mt.innerHTML = min.toString() + ':';
st.innerHTML = ((sec < 10) ? '0' : '') + sec.toString();
}, 1000);
}
document.addEventListener('keydown', (e) => {
let key = e.key;
const cl = l(index);
if (wrong > 0 && key === 'Backspace') {
wrong--;
w(wrong).remove();
return;
}
if (key.match(/^[a-zA-Z"'\s]+$/) && key.length === 1) {
if (index === 0 && !running) {
start();
}
if (cl.innerHTML === key.toLowerCase() && wrong === 0) {
cl.classList.add('correct');
index++;
} else if (key !== ' ') {
let w = document.createElement('DIV');
w.classList.add('letter');
w.classList.add('incorrect');
w.id = "w" + wrong;
w.innerHTML = key;
wrong++;
if (index > 0) l(index - 1).appendChild(w);
else {
let n = l(index);
n.parentNode.insertBefore(w, n);
}
}
cl.classList.remove('cursor');
l(index).classList.add('cursor');
}
});
function l(index) {
return document.getElementById('l' + index);
}
function w(index) {
return document.getElementById('w' + index);
}
function randomRange(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
initTest();
#import url('https://fonts.googleapis.com/css2?family=Roboto+Mono:ital,wght#0,100;0,200;0,300;0,400;0,500;0,600;0,700;1,100;1,200;1,300;1,400;1,500;1,600;1,700&display=swap');
* {
font-family: 'Roboto Mono', monospace;
}
body, html {
margin: 0;
width: 100%;
height: 100%;
overflow: hidden;
}
body {
background-color: #0f0f0f;
--accent: yellow;
--gray: #ababab;
--dark-gray: #8f8f8f;
user-select: none;
-moz-user-select: none;
-ms-user-select: none;
-webkit-user-select: none;
}
.header {
margin: 10px 150px;
}
.title {
font-size: 50px;
font-weight: 200;
color: white;
}
#text {
color: var(--gray);
margin: 20px 150px;
text-align: left;
}
.timer {
color: var(--dark-gray);
font-size: 50px;
font-weight: 300;
text-align: center;
margin: 100px 0 0;
}
.txt-active {
color: white;
transition: color .7s ease;
}
#min, #sec {
display: inline;
}
.word {
display: inline;
}
.letter {
display: inline;
font-weight: 200;
font-size: 24px;
}
.correct {
color: white;
}
.incorrect {
color: #d26f6f;
}
.cursor:before {
position: absolute;
width: 2px;
height: 30px;
background: var(--accent);
content: ' ';
}
.curs-fade:before {
animation: cursor-fade alternate-reverse .8s infinite;
}
#keyframes cursor-fade {
80% {opacity: 1}
0% {opacity: 0}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="styles/style.css">
<title>Typeracer++</title>
</head>
<body>
<div class="header">
<div class="title">typeracer++</div>
</div>
<div class="test">
<div class="timer"><div id="min">0:</div><div id="sec">00</div></div>
<div id="text"></div>
</div>
<script type="text/javascript" src="scripts/game.js"></script>
</body>
</html>
This question already has answers here:
How to add a background image on top of a previous background image?
(1 answer)
Can I have multiple background images using CSS?
(8 answers)
Why does z-index not work?
(10 answers)
Closed 3 years ago.
I want to set a z-index to a background img.
I want the .player background to be always displayed, even when in the same box I have another class with another background.
If you click the right button you'll see that at the the .player goes to the blue box another class will be added. The .player background must be always displayed.
Why z-index is not working? is there any alternative?
Thank you
let moveCounter = 0;
let playerOne = {
currentWeapon: "w1"
}
var grid = document.getElementById("grid-box");
for (var i = 0; i <= 8; i++) {
var square = document.createElement("div");
square.className = 'square';
square.id = 'square' + i;
grid.appendChild(square);
}
$("#square" + 0).addClass("player")
$("#square" + 3).addClass("w3")
function getWeapon(ele) {
let classList = $(ele).attr("class").split(' ');
for (let i = 0; i < classList.length; i += 1) {
if (classList[i][0] === "w") {
$(ele).addClass(playerOne.currentWeapon)
playerOne.currentWeapon = classList[i];
$(ele).removeClass(playerOne.currentWeapon)
return classList[i]
}
}
}
$('#right-button').on('click', function() {
$("#square" + moveCounter).removeClass("player")
moveCounter += 1;
$("#square" + moveCounter).addClass("player")
getWeapon("#square" + moveCounter);
});
#grid-box {
width: 420px;
height: 220px;
}
#grid-box>div.square {
font-size: 1rem;
vertical-align: top;
display: inline-block;
width: 10%;
height: 10%;
box-sizing: border-box;
border: 1px solid #000;
}
.player {
background: url(http://placekitten.com/200/300) no-repeat 0 0;
z-index: 1;
}
.w1 {
background: url(https://preview.ibb.co/ntRarR/watermark3.png) no-repeat center center;
z-index: 0;
}
.w3 {
background-color: blue;
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<div id="grid-box"></div>
<button class="d-pad-button" id="right-button">Right button</button>
Thank you very much guys.
The problem is the class order in the css file. More info can be found here
Change:
.player {
background: url(http://placekitten.com/200/300) no-repeat 0 0;
z-index: 1;
}
.w1 {
background: url(https://preview.ibb.co/ntRarR/watermark3.png) no-repeat center center;
z-index: 0;
}
To:
.w1 {
background: url(https://preview.ibb.co/ntRarR/watermark3.png) no-repeat center center;
z-index: 0;
}
.player {
background: url(http://placekitten.com/200/300) no-repeat 0 0;
z-index: 1;
}
Demo
let moveCounter = 0;
let playerOne = {
currentWeapon: "w1"
}
var grid = document.getElementById("grid-box");
for (var i = 0; i <= 8; i++) {
var square = document.createElement("div");
square.className = 'square';
square.id = 'square' + i;
grid.appendChild(square);
}
$("#square" + 0).addClass("player")
$("#square" + 3).addClass("w3")
function getWeapon(ele) {
let classList = $(ele).attr("class").split(' ');
for (let i = 0; i < classList.length; i += 1) {
if (classList[i][0] === "w") {
$(ele).addClass(playerOne.currentWeapon)
playerOne.currentWeapon = classList[i];
$(ele).removeClass(playerOne.currentWeapon)
return classList[i]
}
}
}
$('#right-button').on('click', function() {
$("#square" + moveCounter).removeClass("player")
moveCounter += 1;
$("#square" + moveCounter).addClass("player")
getWeapon("#square" + moveCounter);
});
#grid-box {
width: 420px;
height: 220px;
}
#grid-box>div.square {
font-size: 1rem;
vertical-align: top;
display: inline-block;
width: 10%;
height: 10%;
box-sizing: border-box;
border: 1px solid #000;
}
.w1 {
background: url(https://preview.ibb.co/ntRarR/watermark3.png) no-repeat center center;
z-index: 0;
}
.player {
background: url(http://placekitten.com/200/300) no-repeat 0 0;
z-index: 1;
}
.w3 {
background-color: blue;
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<div id="grid-box"></div>
<button class="d-pad-button" id="right-button">Right button</button>
https://codepen.io/anon/pen/EOrRXo
This is my code so far. It just uses JS to generate a bunch of styled divs. I don't know how to input a picture instead of a string to fill in my divs. They all have values that I add up to generate each players' score to use bitwise "&" calculation to determine when someone has won. There's a play again button that works but it's broken for you because the image is local. Also it's extreme so it's spinning and I'm sorry if that annoys you.
HTML:
<!DOCTYPE html>
<html>
<head>
<title>EXTREME TIC TAC TOE</title>
<link type="text/css" rel="stylesheet" href="css/style.css">
<script src="js/script.js"></script>
</head>
<body onload = "startGame();">
<h2 id="game-message"> Tic Tac Toe </h2>
<div id="game-board">
</div>
<div id="restartButton" >
<img src="img/lets-play.gif" id="button" onclick="restartGame();">
</div>
</body>
</html>
CSS
/* CSS */
* {margin: 0; padding: 0; user-select: none; text-transform: uppercase;}
body {background-image: url('../img/name.type'); }
h2#game-message
{
font-size: 60px;
font-family: Tahoma;
margin-bottom: 15px;
text-align: center;
}
div#game-board
{
overflow: hidden;
margin: 20px auto;
width:870px;
}
div[id^="row-"] {clear: both;}
div [id^="row-"] div
{
//border: 30px solid plum;
height: 270px;
width: 270px;
float: left;
text-align: center;
font-family: Tahoma;
font-size: 175px;
border-width: 15px;
border-style: solid;
border-image: url('../img/border.jpg') 25% repeat;
}
div#row-1 div {border-top: none;}
div#row-3 div {border-bottom: none;}
div[id^="row-"] div:first-child {border-left: none}
div[id^="row-"] div:last-child {border-right: none}
#button
{
color: white;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
border-width: 5px;
border-style: solid;
border-image: url('../img/borderr.png') 25% round;
}
#restartButton
{
position: absolute;
left: 880px;
top: 1075px;
}
#keyframes rotation
{
from {
transform: rotate(0deg);
}
to {
transform: rotate(359deg);
}
}
#keyframes slide {
0% {left: 0;}
100% { left: 1500px;}
}
#game-board
{
position: relative;
}
JS
//JAVASCRIPT
var markers = ["X", "O"];
//var players = [];
var players = ["Max", "Dennis"];
var totals = [];
var winCodes = [7,56,73,84,146,273,292,448];
var whoseTurn = 0;
var gameOver = false;
var speed = [2, 2];
// Play again button
function restartGame()
{
startGame();
}
function startGame() // Choose your names, and display them in the header message.
{
// makes board spin initially
document.getElementById("game-board").style.animation = "rotation 4s infinite linear";
//players[0] = prompt("Player 1 NAME:");
//players[1] = prompt("Player 2 NAME:");
var counter = 1;
var innerDivs = "";
for (i = 1; i <=3; i++)
{
innerDivs += '<div id="row-' + i + '">';
for (j = 1; j <= 3; j++)
{
innerDivs += '<div onclick="playGame(this,' + counter + ');"></div>';
counter *= 2;
}
innerDivs += '</div>';
}
document.getElementById("game-board").innerHTML = innerDivs;
totals = [0, 0];
gameOver = false;
document.getElementById("game-message").innerText = "IT'S YOUR TURN " + players[whoseTurn];
}
function playGame(clickedDiv, divValue)
{
if (!gameOver)
{
// changes speed depending on how many turns each player has done
speed[whoseTurn]++;
document.getElementById("game-board").style.animation = "rotation "+ 8 / speed[whoseTurn] + "s infinite linear";
// Adds X or O depending on whoseTurn
clickedDiv.innerText = markers[whoseTurn];
// adds up total each time a player "moves" to track a win condition
totals[whoseTurn] += divValue;
// calls isWin() function to see if someone won
if (isWin())
{
document.getElementById("game-message").innerText = "WOW VERY COOL " + players[whoseTurn] + " YOU WON";
document.getElementById("game-board").style.animation = "slide 2s forwards, rotation "+ 8 / speed[whoseTurn] + "s infinite linear";
}
else if (gameOver)
{
document.getElementById("game-message").innerText = "YOU BOTH FAILED";
}
else
{
// Switches turn each click
if (whoseTurn) whoseTurn = 0; else whoseTurn = 1;
// disables onclick tag after clicked so it cannot be used >1 times.
clickedDiv.attributes["0"].nodeValue = "";
// Displays text for which turn it is
document.getElementById("game-message").innerText = "IT'S YOUR TURN " + players[whoseTurn];
}
}
}
// win code logic
function isWin()
{
for (i = 0; i < winCodes.length; i++)
{
if ((totals[whoseTurn] & winCodes[i]) == winCodes[i]) {gameOver = true; return true;}
}
if (totals[0] + totals[1] == 511) {gameOver = true;}
return false;
}
You can start by replacing the markers array with (or creating a new array, such as markerImages) image elements.
Then replace clickedDiv.innerText with clickedDiv.innerHTML.
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.