Does #id override the :hover change? - javascript

I've seen different similar answers but none with the level of nesting I'm dealing with. I have two sets of buttons, circular ones and rectangular ones that I want the background to change to white on hover. The only thing I have been able to successfully change is the text color for the rectangular ones.
I previously had the button styles inline and thought that was the issue. Guess not :/
Does the ID override the :hover change? And if so do I need to reformat all of my buttons? Thank you!
(previous code solutions involve jquery and I have no knowledge of it whatsoever)
/*
CS 81 Final - Noah Derby
*/
//Global Variables
"use strict";
let gameActive = false;
let dealerValue = 0;
let playerValue = 0;
let buttons = document.getElementsByTagName('button');
let totalAmount = document.getElementById('betAmount');
let bank = document.getElementById('bank');
//Card Functions and
function Card(value, name, suit) {
this.value = value;
this.name = name
this.suit = suit
}
function newDeck() {
let suits = ['Hearts','Diamonds','Spades','Clubs'];
let names = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'];
let deck = []
for(let i of suits) {
for(let n=0; n < names.length; n++) {
deck.push(new Card(n+1, names[n], i));
}
}
for (let i = deck.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
const temp = deck[i];
deck[i] = deck[j];
deck[j] = temp;
}
return deck;
}
function addTo(player, card){
let ascii_char;
let div = document.createElement('card');
div.className = 'card';
if(card.suit === 'Diamonds'){
ascii_char = "♦";
div.style.color = 'red';
} else if (card.suit === 'Hearts') {
ascii_char = '♥'
div.style.color = 'red';
} else {
ascii_char = "&" + card.suit.toLowerCase() + ";"
}
div.innerHTML = "<span class='number'>" + card.name + "</span><span class='suit'>" + ascii_char + "</span>";
if(player.id === "dealerTotal"){
document.querySelector(".dealerCards").appendChild(div);
} else {
document.querySelector(".playerCards").appendChild(div);
}
if (card.value > 10){
player.value = parseInt(player.value, 10) + 10;
} else if (card.value === 1) {
let handValue = parseInt(player.value, 10);
if(handValue <= 10) {
player.value = handValue + 11
} else {
player.value = handValue + 1
}
} else {
player.value = parseInt(player.value, 10) + card.value;
}
}
function clearCards() {
document.querySelector(".dealerCards").innerHTML = "";
document.querySelector(".playerCards").innerHTML = "";
}
//Button Handlers
for (let i=0; i < buttons.length; i++) {
buttons[i].addEventListener('click', () => {
let playerTotal = document.getElementById("playerTotal");
let dealerTotal = document.getElementById("dealerTotal");
let bankValue = parseInt(bank.value, 10);
let amountValue = parseInt(totalAmount.value, 10);
let cards = newDeck();
switch (buttons[i].id) {
case "one":
if(!gameActive){
totalAmount.value = parseInt(totalAmount.value, 10) + 1;
break;
}
break;
case "five":
if(!gameActive){
totalAmount.value = parseInt(totalAmount.value, 10) + 5;
break;
}
break;
case "ten":
if(!gameActive){
totalAmount.value = parseInt(totalAmount.value, 10) + 10;
break;
}
break;
case "twentyfive":
if(!gameActive){
totalAmount.value = parseInt(totalAmount.value, 10) + 25;
break;
}
break;
case "hundred":
if(!gameActive){
totalAmount.value = parseInt(totalAmount.value, 10) + 100;
break;
}
break
case "fivehundred":
if(!gameActive){
totalAmount.value = parseInt(totalAmount.value, 10) + 500;
break;
}
break;
case "thousand":
if(!gameActive){
totalAmount.value = parseInt(totalAmount.value, 10) + 1000;
break;
}
break;
case "reset":
if (!gameActive){
totalAmount.value = 0;
break;
}
break;
case "submit":
if(!gameActive){
if (bankValue === 0) {
alert("No funds available :(");
break;
} else if (amountValue === 0) {
alert("Please Enter a valid amount")
break;
} else if(amountValue > bankValue){
totalAmount.value = bank.value;
bank.value = 0;
} else{
bank.value = bankValue - amountValue;
}
clearCards();
playerTotal.value = dealerTotal.value = '0';
addTo(playerTotal, cards.pop());
addTo(playerTotal, cards.pop());
addTo(dealerTotal, cards.pop());
dealerTotal.style.color = "transparent";
gameActive = true;
break;
}
break;
case "hit":
if(gameActive) {
addTo(playerTotal, cards.pop())
if(parseInt(playerTotal.value, 10) > 21){
alert(`You lost $${amountValue} :( \n Submit another bet to play again!`);
dealerTotal.style.color = "black";
totalAmount.value= '0';
gameActive = false;
break;
}
}
break;
case 'stand':
if (gameActive) {
playerValue = parseInt(playerTotal.value, 10);
while(parseInt(dealerTotal.value, 10) <= 17){
addTo(dealerTotal, cards.pop());
}
dealerValue = parseInt(dealerTotal.value, 10);
if (dealerValue > 21){
alert(`You won $${amountValue*2}!!!`);
bank.value = bankValue + amountValue * 2;
totalAmount.value = 0;
gameActive = false;
dealerTotal.style.color = "black";
break;
}
if (playerValue < dealerValue) {
alert(`You lost $${amountValue} :( \n Submit another bet to play again!`);
totalAmount.value= '0';
} else if (playerValue > dealerValue) {
alert(`You won $${amountValue*2}!!!`);
bank.value = bankValue + amountValue * 2;
totalAmount.value = '0';
} else {
alert(`Its a tie! Funds refunded!`);
bank.value = bankValue + amountValue;
totalAmount.value= '0';
}
dealerTotal.style.color = "black";
gameActive = false;
}
break;
}
}, false)
}
/* CS 81 Final - Noah Derby */
body {
background-image: url('https://cdn.hipwallpaper.com/i/46/65/hEiUkp.jpg');
background-size: cover;
font-family: Verdana, sans-serif, bold;
font-weight: bold;
margin: 5px;
}
header {
text-align: center;
font-size: 50px;
margin: 50px 500px -50px;
}
label{
font-size: 25px;
}
input{
font-size: 25px;
color: black;
background-color: white;
}
div {
margin: 5px;
}
.economyWrap{
position: relative;
float: left;
width: 480px;
height: 500px;
top: 100px;
left: 50px;
}
.playWrap{
position: relative;
border: 5px solid black;
float: left;
top: 100px;
width: 260px;
height: 300px;
margin-left: 140px;
}
.textContainer{
padding: 5px;
background: rgba(0, 128, 0, 0.02);
margin: 200px 0 0 125px;
width: 400px;
float: left;
}
.playButtonContainer{
position: absolute;
margin: 17px;
bottom:-90px;
}
.earningsContainer{
position: absolute;
width: 450px;
height: 35px;
padding: 5px;
top:0;
left:85px;
}
.submitContainer {
margin: auto;
position: absolute;
width: 340px;
bottom: 220px;
left: 120px;
}
.chipContainer{
margin: auto;
position: absolute;
height: 210px;
width: 250px;
left: 140px;
bottom: 0;
}
/*
Buttons
*/
button.chip{
display: inline-block;
text-align: center;
font-family: "Verdana", sans-serif;
font-size: 15px;
font-weight: bold;
border-radius: 50%;
height: 52px;
width: 52px;
margin: 5px;
cursor: pointer;
transition-duration: .5s;
}
#one {
background-color: rgba(34,31,32,0.95);
color:white;
border: 5px solid rgba(209,212,213,0.95);
}
#five {
background-color: rgba(242,122,128,0.95);
color: rgba(148,30,28,0.95);
border: 5px solid rgba(235,53,45,0.95);
}
#ten {
background-color: rgba(169,219,203,0.95);
color: rgba(13,45,76,0.95);
border: 5px solid rgba(3,90,136,0.95);
}
#twentyfive {
background-color: rgba(235,232,64,0.95);
color: rgba(51,123,18,0.95);
border: 5px solid rgba(57,134,63,0.95);
}
#hundred {
background-color: #fdf049;
color: rgb(235,53,45);
border: 5px solid rgb(235,53,45);
}
#fivehundred {
background-color: #b6b0d5;
color: rgb(71,45,126);
border: 5px solid rgb(126,70,155);
}
#thousand {
background-color: #fffef6;
color: rgb(34,31,31);
border: 5px solid #59585a;
}
button.bet {
display: inline-block;
border-radius: 10px;
border: 4px solid saddlebrown;
text-align: center;
font-family: "Verdana", sans-serif;
font-size: 14px;
font-weight: bold;
height: 50px;
width: 100px;
margin: 5px;
cursor: pointer;
transition-duration: .5s;
}
#submit {
background-color: #358535;
}
#reset {
background-color: yellow;
}
#hit {
background-color: lightcoral;
}
#stand {
background-color: lightgreen;
}
.card{
background-color: white;
width:40px;
height:60px;
border:1px solid #151718;
float:left;
border-radius:2px;
}
.number, .suit{
width:100%;
display:block;
text-align:center;
padding-top:8px;
}
button:hover {
background-color: white;
}
<!DOCTYPE html>
<html lang="en">
<!-- CS 81 Final Project - Noah Derby-->
<!-- A simple blackjack game. I hope you enjoy!!!!!!-->
<head>
<meta charset="UTF-8">
<title>Blackjack!</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<header>Blackjack!</header>
<div class="economyWrap">
<div class="earningsContainer">
<label for="bank" style="font-size: 25px;">Your Balance is: $ </label><input type="number" id="bank" value="1000" style="width: 100px;" disabled>
</div>
<div class="chipContainer">
<button id="one" class="chip">1</button>
<button id="five" class="chip">5</button>
<button id="ten" class="chip" >10</button>
<button id="twentyfive" class="chip">25</button>
<button id="hundred" class="chip">100</button>
<button id="fivehundred" class="chip">500</button>
<button id="thousand" class="chip">1k</button>
</div>
<div class="submitContainer">
<label for="betAmount" style="font-size: 25px;">Bet Amount: $ </label><input type="number" id="betAmount" value="0" style="margin:5px; width: 100px;" disabled>
<button id="reset" class="bet">Reset</button>
<button id="submit" class="bet">Submit</button>
</div>
</div>
<div class="playWrap">
<div class="dealerContainer">
<label for="dealerTotal">Dealer Total: </label><input value="0" id="dealerTotal" style=" width: 50px;" disabled>
<div class="dealerCards"></div>
</div>
<div class="playerContainer" style="position: absolute; bottom:0;">
<label for="playerTotal">Your Total: </label><input value="0" id="playerTotal" style="bottom:0; width: 50px;" disabled>
<div class="playerCards"></div>
</div>
<div class="playButtonContainer">
<button class="bet" id="hit" style="background-color: lightgreen;">Hit</button>
<button class="bet" id="stand" style="background-color: lightcoral;">Stand</button>
</div>
</div>
<div class="textContainer">
<h2>Welcome to Blackjack!</h2>
<h4>
To start, click the corresponding chips to place your bets and click "Submit" to start the game!
The goal is to reach 21, so you can decide to either hit (gain another card) or stand (wait for the dealer).
Whoever is closer to 21 without going over wins!
</h4>
</div>
</body>
<script src="main.js"></script>
</html>

Question - Does the ID override the :hover change?
Answer -
The style rule for a:hover will override the paragraph as long as it is written in the CSS after the rule for p or #id.
The problem is that the selector handling your :hover behavior has a lower Specificity than the rule for the default behavior (p#id selector).
Question - If so do I need to reformat all of my buttons?
Answer - No, you don't need to reformat all the buttons as you can use !important on the button:hover in the CSS file.
/*
CS 81 Final - Noah Derby
*/
//Global Variables
"use strict";
let gameActive = false;
let dealerValue = 0;
let playerValue = 0;
let buttons = document.getElementsByTagName('button');
let totalAmount = document.getElementById('betAmount');
let bank = document.getElementById('bank');
//Card Functions and
function Card(value, name, suit) {
this.value = value;
this.name = name
this.suit = suit
}
function newDeck() {
let suits = ['Hearts','Diamonds','Spades','Clubs'];
let names = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'];
let deck = []
for(let i of suits) {
for(let n=0; n < names.length; n++) {
deck.push(new Card(n+1, names[n], i));
}
}
for (let i = deck.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
const temp = deck[i];
deck[i] = deck[j];
deck[j] = temp;
}
return deck;
}
function addTo(player, card){
let ascii_char;
let div = document.createElement('card');
div.className = 'card';
if(card.suit === 'Diamonds'){
ascii_char = "♦";
div.style.color = 'red';
} else if (card.suit === 'Hearts') {
ascii_char = '♥'
div.style.color = 'red';
} else {
ascii_char = "&" + card.suit.toLowerCase() + ";"
}
div.innerHTML = "<span class='number'>" + card.name + "</span><span class='suit'>" + ascii_char + "</span>";
if(player.id === "dealerTotal"){
document.querySelector(".dealerCards").appendChild(div);
} else {
document.querySelector(".playerCards").appendChild(div);
}
if (card.value > 10){
player.value = parseInt(player.value, 10) + 10;
} else if (card.value === 1) {
let handValue = parseInt(player.value, 10);
if(handValue <= 10) {
player.value = handValue + 11
} else {
player.value = handValue + 1
}
} else {
player.value = parseInt(player.value, 10) + card.value;
}
}
function clearCards() {
document.querySelector(".dealerCards").innerHTML = "";
document.querySelector(".playerCards").innerHTML = "";
}
//Button Handlers
for (let i=0; i < buttons.length; i++) {
buttons[i].addEventListener('click', () => {
let playerTotal = document.getElementById("playerTotal");
let dealerTotal = document.getElementById("dealerTotal");
let bankValue = parseInt(bank.value, 10);
let amountValue = parseInt(totalAmount.value, 10);
let cards = newDeck();
switch (buttons[i].id) {
case "one":
if(!gameActive){
totalAmount.value = parseInt(totalAmount.value, 10) + 1;
break;
}
break;
case "five":
if(!gameActive){
totalAmount.value = parseInt(totalAmount.value, 10) + 5;
break;
}
break;
case "ten":
if(!gameActive){
totalAmount.value = parseInt(totalAmount.value, 10) + 10;
break;
}
break;
case "twentyfive":
if(!gameActive){
totalAmount.value = parseInt(totalAmount.value, 10) + 25;
break;
}
break;
case "hundred":
if(!gameActive){
totalAmount.value = parseInt(totalAmount.value, 10) + 100;
break;
}
break
case "fivehundred":
if(!gameActive){
totalAmount.value = parseInt(totalAmount.value, 10) + 500;
break;
}
break;
case "thousand":
if(!gameActive){
totalAmount.value = parseInt(totalAmount.value, 10) + 1000;
break;
}
break;
case "reset":
if (!gameActive){
totalAmount.value = 0;
break;
}
break;
case "submit":
if(!gameActive){
if (bankValue === 0) {
alert("No funds available :(");
break;
} else if (amountValue === 0) {
alert("Please Enter a valid amount")
break;
} else if(amountValue > bankValue){
totalAmount.value = bank.value;
bank.value = 0;
} else{
bank.value = bankValue - amountValue;
}
clearCards();
playerTotal.value = dealerTotal.value = '0';
addTo(playerTotal, cards.pop());
addTo(playerTotal, cards.pop());
addTo(dealerTotal, cards.pop());
dealerTotal.style.color = "transparent";
gameActive = true;
break;
}
break;
case "hit":
if(gameActive) {
addTo(playerTotal, cards.pop())
if(parseInt(playerTotal.value, 10) > 21){
alert(`You lost $${amountValue} :( \n Submit another bet to play again!`);
dealerTotal.style.color = "black";
totalAmount.value= '0';
gameActive = false;
break;
}
}
break;
case 'stand':
if (gameActive) {
playerValue = parseInt(playerTotal.value, 10);
while(parseInt(dealerTotal.value, 10) <= 17){
addTo(dealerTotal, cards.pop());
}
dealerValue = parseInt(dealerTotal.value, 10);
if (dealerValue > 21){
alert(`You won $${amountValue*2}!!!`);
bank.value = bankValue + amountValue * 2;
totalAmount.value = 0;
gameActive = false;
dealerTotal.style.color = "black";
break;
}
if (playerValue < dealerValue) {
alert(`You lost $${amountValue} :( \n Submit another bet to play again!`);
totalAmount.value= '0';
} else if (playerValue > dealerValue) {
alert(`You won $${amountValue*2}!!!`);
bank.value = bankValue + amountValue * 2;
totalAmount.value = '0';
} else {
alert(`Its a tie! Funds refunded!`);
bank.value = bankValue + amountValue;
totalAmount.value= '0';
}
dealerTotal.style.color = "black";
gameActive = false;
}
break;
}
}, false)
}
/* CS 81 Final - Noah Derby */
body {
background-image: url('https://cdn.hipwallpaper.com/i/46/65/hEiUkp.jpg');
background-size: cover;
font-family: Verdana, sans-serif, bold;
font-weight: bold;
margin: 5px;
}
header {
text-align: center;
font-size: 50px;
margin: 50px 500px -50px;
}
label{
font-size: 25px;
}
input{
font-size: 25px;
color: black;
background-color: white;
}
div {
margin: 5px;
}
.economyWrap{
position: relative;
float: left;
width: 480px;
height: 500px;
top: 100px;
left: 50px;
}
.playWrap{
position: relative;
border: 5px solid black;
float: left;
top: 100px;
width: 260px;
height: 300px;
margin-left: 140px;
}
.textContainer{
padding: 5px;
background: rgba(0, 128, 0, 0.02);
margin: 200px 0 0 125px;
width: 400px;
float: left;
}
.playButtonContainer{
position: absolute;
margin: 17px;
bottom:-90px;
}
.earningsContainer{
position: absolute;
width: 450px;
height: 35px;
padding: 5px;
top:0;
left:85px;
}
.submitContainer {
margin: auto;
position: absolute;
width: 340px;
bottom: 220px;
left: 120px;
}
.chipContainer{
margin: auto;
position: absolute;
height: 210px;
width: 250px;
left: 140px;
bottom: 0;
}
/*
Buttons
*/
button.chip{
display: inline-block;
text-align: center;
font-family: "Verdana", sans-serif;
font-size: 15px;
font-weight: bold;
border-radius: 50%;
height: 52px;
width: 52px;
margin: 5px;
cursor: pointer;
transition-duration: .5s;
}
#one {
background-color: rgba(34,31,32,0.95);
color:white;
border: 5px solid rgba(209,212,213,0.95);
}
#five {
background-color: rgba(242,122,128,0.95);
color: rgba(148,30,28,0.95);
border: 5px solid rgba(235,53,45,0.95);
}
#ten {
background-color: rgba(169,219,203,0.95);
color: rgba(13,45,76,0.95);
border: 5px solid rgba(3,90,136,0.95);
}
#twentyfive {
background-color: rgba(235,232,64,0.95);
color: rgba(51,123,18,0.95);
border: 5px solid rgba(57,134,63,0.95);
}
#hundred {
background-color: #fdf049;
color: rgb(235,53,45);
border: 5px solid rgb(235,53,45);
}
#fivehundred {
background-color: #b6b0d5;
color: rgb(71,45,126);
border: 5px solid rgb(126,70,155);
}
#thousand {
background-color: #fffef6;
color: rgb(34,31,31);
border: 5px solid #59585a;
}
button.bet {
display: inline-block;
border-radius: 10px;
border: 4px solid saddlebrown;
text-align: center;
font-family: "Verdana", sans-serif;
font-size: 14px;
font-weight: bold;
height: 50px;
width: 100px;
margin: 5px;
cursor: pointer;
transition-duration: .5s;
}
#submit {
background-color: #358535;
}
#reset {
background-color: yellow;
}
#hit {
background-color: lightcoral;
}
#stand {
background-color: lightgreen;
}
.card{
background-color: white;
width:40px;
height:60px;
border:1px solid #151718;
float:left;
border-radius:2px;
}
.number, .suit{
width:100%;
display:block;
text-align:center;
padding-top:8px;
}
button:hover {
background-color: white !important;
}
<!DOCTYPE html>
<html lang="en">
<!-- CS 81 Final Project - Noah Derby-->
<!-- A simple blackjack game. I hope you enjoy!!!!!!-->
<head>
<meta charset="UTF-8">
<title>Blackjack!</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<header>Blackjack!</header>
<div class="economyWrap">
<div class="earningsContainer">
<label for="bank" style="font-size: 25px;">Your Balance is: $ </label><input type="number" id="bank" value="1000" style="width: 100px;" disabled>
</div>
<div class="chipContainer">
<button id="one" class="chip">1</button>
<button id="five" class="chip">5</button>
<button id="ten" class="chip" >10</button>
<button id="twentyfive" class="chip">25</button>
<button id="hundred" class="chip">100</button>
<button id="fivehundred" class="chip">500</button>
<button id="thousand" class="chip">1k</button>
</div>
<div class="submitContainer">
<label for="betAmount" style="font-size: 25px;">Bet Amount: $ </label><input type="number" id="betAmount" value="0" style="margin:5px; width: 100px;" disabled>
<button id="reset" class="bet">Reset</button>
<button id="submit" class="bet">Submit</button>
</div>
</div>
<div class="playWrap">
<div class="dealerContainer">
<label for="dealerTotal">Dealer Total: </label><input value="0" id="dealerTotal" style=" width: 50px;" disabled>
<div class="dealerCards"></div>
</div>
<div class="playerContainer" style="position: absolute; bottom:0;">
<label for="playerTotal">Your Total: </label><input value="0" id="playerTotal" style="bottom:0; width: 50px;" disabled>
<div class="playerCards"></div>
</div>
<div class="playButtonContainer">
<button class="bet" id="hit" style="background-color: lightgreen;">Hit</button>
<button class="bet" id="stand" style="background-color: lightcoral;">Stand</button>
</div>
</div>
<div class="textContainer">
<h2>Welcome to Blackjack!</h2>
<h4>
To start, click the corresponding chips to place your bets and click "Submit" to start the game!
The goal is to reach 21, so you can decide to either hit (gain another card) or stand (wait for the dealer).
Whoever is closer to 21 without going over wins!
</h4>
</div>
</body>
<script src="main.js"></script>
</html>

Related

Trigger function when a div enters another div

I'm new to coding so I know nothing to very little, but I want to learn. I've been working on this for the past few days and i've hit a wall.Got the function to work with a click but I want to trigger the function with the space key when the green div enters the divs with the function. Can it be done? Heres the code i've wrieten sofar.
HTML
const main = document.querySelector('.main')
const rowOne = document.querySelector('.row-one')
const rowThree = document.querySelector('.row-three')
const green = document.querySelector('.green')
let xAxis = 0
let yAxis = 0
let num = 50
let count = 50
function control(e) {
switch (e.key) {
case 'ArrowLeft':
console.log('worked');
xAxis -= 50;
muncher.style.left = xAxis + 'px';
break;
case 'ArrowRight':
xAxis += 50;
muncher.style.left = xAxis + 'px';
break;
case 'ArrowUp':
yAxis -= 50;
muncher.style.top = yAxis + 'px';
break;
case 'ArrowDown':
yAxis += 50;
muncher.style.top =yAxis + 'px';
break;
}
}
document.addEventListener('keydown', control)
let num1 = Math.floor(Math.random() * num)
function indexText1(e) {
if(num1 % 5 === 0) {
rowOne.textContent = 'WIN!!'
}else{
rowOne.textContent = 'LOOSE!!'
}
switch (e.key) {
case '90':
console.log('there')
}
}
rowOne.textContent = num1
rowOne.addEventListener('click', indexText1)
let num3 = Math.floor(Math.random() * num)
function indexText3(e) {
if(num1 % 5 === 0) {
rowThree.textContent = 'WIN!!'
}else{
rowThree.textContent = 'LOOSE!!'
}
}
rowThree.textContent = num3
rowThree.addEventListener('click', indexText3)
#main {
position: absolute;
width: 404px;
height: 304px;
border: 5px solid black;
margin: 5px;
}
.row-one {
outline: none;
width: 398px;
height: 65px;
border: 1px solid red;
margin-top: 2px;
margin-left: 2px;
margin-right: 2px;
}
.row-two {
width: 398px;
height: 65px;
border: 1px solid red;
margin-left: 2px;
}
.row-three {
outline: none;
width: 398px;
height: 65px;
border: 1px solid red;
margin-top: 2px;
margin-left: 2px;
margin-right: 2px;
}
.row-four {
outline: none;
width: 398px;
height: 65px;
border: 1px solid red;
margin-top: 2px;
margin-left: 2px;
margin-right: 2px;
}
.green {
position: absolute;
width: 25px;
height: 25px;
background-color: green;
}
<div id="main">
<div class="row-one"></div>
<div class="row-two"></div>
<div class="row-three"></div>
<div class="row-four"></div>
<div class="green"></div>
</div>

Why are my images invisible even after adding background image with css?

I am trying to build a game similar to the snake game, except it is with shark and a fish. I have written a program that works exactly like the game I wanted to make, but when I tried using an image instead of background color for shark and fish, the just became invisible. I am quoting the code I have written for this. Please suggest how to change background colors of the thing representing shark and fish to their images. the pictures are in the same folder as the code files.
EDIT: i hosted the images online and they are still not visible....
please pardon if there are any mistakes in my code as i am not very great at programming...
//constants n variables
let inputdir = {x: 0, y: 0};
const eatsound = new Audio('eat.wav');
const gosound = new Audio('gameover.wav');
const movesound = new Audio('move.wav');
const musicsound = new Audio('music.mp3');
let speed = 5;
let score = 0;
let lastPaintTime = 0;
let sharkarr = [
{x: 13, y: 15}
]
fish = {x: 6, y: 7};
//game functions
function main(ctime) {
window.requestAnimationFrame(main);
//console.log(ctime)
if((ctime - lastPaintTime)/1000 < 1/speed){
return;
}
lastPaintTime = ctime;
gameEngine();
}
function isCollide(sharkarr) {
if(sharkarr[0].x >= 18*2 || sharkarr[0].x <= -18 || sharkarr[0].y >= 18*2 || sharkarr[0].y <= -18){
return true;
}
}
function gameEngine(){
// updating fish, shark
if(isCollide(sharkarr)){
gosound.play();
musicsound.pause();
inputdir = {x: 0, y: 0};
setTimeout(() => {
alert("GAME OVER!");
}, 2000);
sharkarr = [{x: 13, y: 15}];
musicsound.play();
score = 0;
scoreBox.innerHTML = "Score: " + score;
}
//fish eaten = score+ + fish moved
if(sharkarr[0].y === fish.y && sharkarr[0].x === fish.x){
eatsound.play();
score += 1;
scoreBox.innerHTML = "Score: " + score
let a = 1;
let b = 18;
fish = {x: Math.round(a + (b - a)*Math.random()), y: Math.round(a + (b - a)*Math.random())}
}
//moving shark
for (let i = sharkarr.length - 2; i>=0 ; i--){
//const element = array[i];
sharkarr[i+1] = {...sharkarr[i]};
}
sharkarr[0].x += inputdir.x;
sharkarr[0].y += inputdir.y;
// display shark
board.innerHTML = "";
sharkarr.forEach((e, index)=>{
sharkelement = document.createElement('div');
sharkelement.style.gridRowStart = e.y;
sharkelement.style.gridColumnStart = e.x;
if(index === 0){
sharkelement.classList.add('shark')
}
else{
sharkelement.classList.add('shark');
}
board.appendChild(sharkelement);
})
// display food
fishelement = document.createElement('div');
fishelement.style.gridRowStart = fish.y;
fishelement.style.gridColumnStart = fish.x;
fishelement.classList.add('fish');
board.appendChild(fishelement);
}
//main logic
window.requestAnimationFrame(main);
window.addEventListener('keydown', e =>{
inputdir = {x: 0, y: 1} //starts the game
movesound.play();
musicsound.play();
switch (e.key) {
case "ArrowUp":
//console.log("ArrowUp");
inputdir.x = 0;
inputdir.y = -1;
break;
case "ArrowDown":
//console.log("ArrowDown");
inputdir.x = 0;
inputdir.y = 1;
break;
case "ArrowLeft":
//console.log("ArrowLeft");
inputdir.x = -1;
inputdir.y = 0;
break;
case "ArrowRight":
//console.log("ArrowRight");
inputdir.x = 1;
inputdir.y = 0;
break;
default:
break;
}
})
*{
padding: 0;
margin: 0;
}
body{
background-color: blue;
}
.body{
background-repeat: no-repeat;
background-size: 100vw 100vh;
width: 100%;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
#bg{
width: 100vw;
height: 100vh;
object-fit: cover;
position: fixed;
left: 0;
right: 0;
top: 0;
bottom: 0;
z-index: -1;
}
#title{
color: white;
border: 2px solid white;
width: 98%;
font-family: Verdana, Geneva, Tahoma, sans-serif;
position: absolute;
top: 1%;
text-align: center;
background-color: green;
font-size: medium;
}
#scoreBox{
color: white;
border: 2px solid white;
width: 98%;
font-family: Verdana, Geneva, Tahoma, sans-serif;
position: absolute;
bottom: 1%;
text-align: center;
background-color: green;
font-size: medium;
}
#board{
width: 98%;
height: 85%;
display: grid;
grid-template-rows: repeat(18, 1fr);
grid-template-columns: repeat(18, 1fr);
border: 10px solid red;
}
.shark{
background-color: #fff;
background-image: url('https://postimg.cc/dDBdCsP4');
background-repeat: no-repeat;
}
.fish{
background-color: yellow;
background-image: url('https://postimg.cc/SYNnd9FV');
background-repeat: no-repeat;
}
<!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">
<title>Eat The Fish</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="body">
<video id="bg" autoplay loop muted>
<source src="bg.mp4">
</video>
<div id="title">EAT THE FISH!!!</div>
<div id="scoreBox">Score: 0</div>
<div id="board"></div>
</div>
</body>
<script src="index.js"></script>
</html>
background-clip is for controlling whether a background image extends beyond its element's boundaries. It is not for embedding video clips in the background, and does not accept a url().
https://developer.mozilla.org/en-US/docs/Web/CSS/background-clip
Your background-image rules should work (provided the path to the images is correct) but they are commented out.
I changed this line:
background-clip: url(bg.mp4);
to
background-image: url(https://picsum.photos/300/200);
background-clip: border-box;
Read more about background-clip
I also added some placeholder images to show that your issue is almost certainly a result of an invalid path to your images.
//constants n variables
let inputdir = {x: 0, y: 0};
const eatsound = new Audio('eat.wav');
const gosound = new Audio('gameover.wav');
const movesound = new Audio('move.wav');
const musicsound = new Audio('music.mp3');
let speed = 5;
let score = 0;
let lastPaintTime = 0;
let sharkarr = [
{x: 13, y: 15}
]
fish = {x: 6, y: 7};
//game functions
function main(ctime) {
window.requestAnimationFrame(main);
//console.log(ctime)
if((ctime - lastPaintTime)/1000 < 1/speed){
return;
}
lastPaintTime = ctime;
gameEngine();
}
function isCollide(sharkarr) {
if(sharkarr[0].x >= 18*2 || sharkarr[0].x <= -18 || sharkarr[0].y >= 18*2 || sharkarr[0].y <= -18){
return true;
}
}
function gameEngine(){
// updating fish, shark
if(isCollide(sharkarr)){
gosound.play();
musicsound.pause();
inputdir = {x: 0, y: 0};
setTimeout(() => {
alert("GAME OVER!");
}, 2000);
sharkarr = [{x: 13, y: 15}];
musicsound.play();
score = 0;
scoreBox.innerHTML = "Score: " + score;
}
//fish eaten = score+ + fish moved
if(sharkarr[0].y === fish.y && sharkarr[0].x === fish.x){
eatsound.play();
score += 1;
scoreBox.innerHTML = "Score: " + score
let a = 1;
let b = 18;
fish = {x: Math.round(a + (b - a)*Math.random()), y: Math.round(a + (b - a)*Math.random())}
}
//moving shark
for (let i = sharkarr.length - 2; i>=0 ; i--){
//const element = array[i];
sharkarr[i+1] = {...sharkarr[i]};
}
sharkarr[0].x += inputdir.x;
sharkarr[0].y += inputdir.y;
// display shark
board.innerHTML = "";
sharkarr.forEach((e, index)=>{
sharkelement = document.createElement('div');
sharkelement.style.gridRowStart = e.y;
sharkelement.style.gridColumnStart = e.x;
if(index === 0){
sharkelement.classList.add('shark')
}
else{
sharkelement.classList.add('shark');
}
board.appendChild(sharkelement);
})
// display food
fishelement = document.createElement('div');
fishelement.style.gridRowStart = fish.y;
fishelement.style.gridColumnStart = fish.x;
fishelement.classList.add('fish');
board.appendChild(fishelement);
}
//main logic
window.requestAnimationFrame(main);
window.addEventListener('keydown', e =>{
inputdir = {x: 0, y: 1} //starts the game
movesound.play();
musicsound.play();
switch (e.key) {
case "ArrowUp":
//console.log("ArrowUp");
inputdir.x = 0;
inputdir.y = -1;
break;
case "ArrowDown":
//console.log("ArrowDown");
inputdir.x = 0;
inputdir.y = 1;
break;
case "ArrowLeft":
//console.log("ArrowLeft");
inputdir.x = -1;
inputdir.y = 0;
break;
case "ArrowRight":
//console.log("ArrowRight");
inputdir.x = 1;
inputdir.y = 0;
break;
default:
break;
}
})
*{
padding: 0;
margin: 0;
}
body{
background-color: blue;
}
.body{
background-image: url(https://picsum.photos/300/200);
background-clip: border-box;
background-repeat: no-repeat;
background-size: 100vw 100vh;
width: 100%;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
#bg{
width: 100vw;
height: 100vh;
object-fit: cover;
position: fixed;
left: 0;
right: 0;
top: 0;
bottom: 0;
z-index: -1;
}
#title{
color: white;
border: 2px solid white;
width: 98%;
font-family: Verdana, Geneva, Tahoma, sans-serif;
position: absolute;
top: 1%;
text-align: center;
background-color: green;
font-size: medium;
}
#scoreBox{
color: white;
border: 2px solid white;
width: 98%;
font-family: Verdana, Geneva, Tahoma, sans-serif;
position: absolute;
bottom: 1%;
text-align: center;
background-color: green;
font-size: medium;
}
#board{
width: 98%;
height: 85%;
display: grid;
grid-template-rows: repeat(18, 1fr);
grid-template-columns: repeat(18, 1fr);
border: 10px solid red;
}
.shark{
background-color: #fff;
background-image: url('https://picsum.photos/30/20');
background-repeat: no-repeat;
}
.fish{
background-color:yellow;
background-image: url('https://picsum.photos/30/20');
background-repeat: no-repeat;
}
<!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">
<title>Eat The Fish</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="body">
<video id="bg" autoplay loop muted>
<source src="bg.mp4">
</video>
<div id="title">EAT THE FISH!!!</div>
<div id="scoreBox">Score: 0</div>
<div id="board"></div>
</div>
</body>
<script src="index.js"></script>
</html>

init function TypeError: Cannot read property 'style' of null

No matter how I wrote the code, I received the same message and I've been trying to fix this since last night, but I don't understand why this is bothering me so much.
I get the message that all these lines are wrong
I work according to my course and this code is from a course that works on video and it doesn't work for me, I've tried a lot of changes but it doesn't work.
document.getElementById('dice-1').style.display = 'block';
document.getElementById('dice-2').style.display = 'block';
var scores, roundScore, activePlayer, gamePlaying;
var lastDice;
function init() {
scores = [0, 0];
activePlayer = 0;
roundScore = 0;
gamePlaying = true;
document.getElementById('dice-1').style.display = 'none';
document.getElementById('dice-2').style.display = 'none';
document.getElementById('score-0').textContent = '0';
document.getElementById('score-1').textContent = '0';
document.getElementById('current-0').textContent = '0';
document.getElementById('current-1').textContent = '0';
document.getElementById('name-0').textContent = 'Player 1';
document.getElementById('name-1').textContent = 'Player 2';
document.querySelector('.player-0-panel').classList.remove('winner');
document.querySelector('.player-1-panel').classList.remove('winner');
document.querySelector('.player-0-panel').classList.remove('active');
document.querySelector('.player-1-panel').classList.remove('active');
document.querySelector('.player-0-panel').classList.add('active');
}
document.querySelector('.btn-roll').addEventListener('click', function() {
if(gamePlaying) {
var dice1 = Math.floor(Math.random() * 6) + 1;
var dice2 = Math.floor(Math.random() * 6) + 1;
document.getElementById('dice-1').style.display = 'block';
document.getElementById('dice-2').style.display = 'block';
document.getElementById('dice-1').src = 'dice-' + dice1 + '.png';
document.getElementById('dice-2').src = 'dice-' + dice2 + '.png';
if (dice1 !== 1 && dice2 !== 1) {
roundScore += dice1 + dice2;
document.querySelector('#current-' + activePlayer).textContent = roundScore;
} else {
nextPlayer();
}
}
});
document.querySelector('.btn-hold').addEventListener('click', function() {
if (gamePlaying) {
scores[activePlayer] += roundScore;
document.querySelector('#score-' + activePlayer).textContent = scores[activePlayer];
var input = document.querySelector('.final-score').value;
var winningScore;
if(input) {
winningScore = input;
} else {
winningScore = 100;
}
// Check if player won the game
if (scores[activePlayer] >= winningScore) {
document.querySelector('#name-' + activePlayer).textContent = 'Winner!';
document.getElementById('dice-1').style.display = 'none';
document.getElementById('dice-2').style.display = 'none';
document.querySelector('.player-' + activePlayer + '-panel').classList.add('winner');
document.querySelector('.player-' + activePlayer + '-panel').classList.remove('active');
gamePlaying = false;
} else {
nextPlayer();
}
}
});
function nextPlayer() {
activePlayer === 0 ? activePlayer = 1 : activePlayer = 0;
roundScore = 0;
document.getElementById('current-0').textContent = '0';
document.getElementById('current-1').textContent = '0';
document.querySelector('.player-0-panel').classList.toggle('active');
document.querySelector('.player-1-panel').classList.toggle('active');
document.getElementById('dice-1').style.display = 'none';
document.getElementById('dice-2').style.display = 'none';
}
document.querySelector('.btn-new').addEventListener('click', init);
init();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link href="https://fonts.googleapis.com/css?family=Lato:100,300,600" rel="stylesheet" type="text/css">
<link href="http://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet" type="text/css">
<link type="text/css" rel="stylesheet" href="style.css">
<title>Pig Game</title>
</head>
<body>
<div class="wrapper clearfix">
<div class="player-0-panel active">
<div class="player-name" id="name-0">Player 1</div>
<div class="player-score" id="score-0">43</div>
<div class="player-current-box">
<div class="player-current-label">Current</div>
<div class="player-current-score" id="current-0">11</div>
</div>
</div>
<div class="player-1-panel">
<div class="player-name" id="name-1">Player 2</div>
<div class="player-score" id="score-1">72</div>
<div class="player-current-box">
<div class="player-current-label">Current</div>
<div class="player-current-score" id="current-1">0</div>
</div>
</div>
<button class="btn-new"><i class="ion-ios-plus-outline"></i>New game</button>
<button class="btn-roll"><i class="ion-ios-loop"></i>Roll dice</button>
<button class="btn-hold"><i class="ion-ios-download-outline"></i>Hold</button>
<input type="text" placeholder="Final Score" class="final-score">
<img src="dice-5.png" alt="Dice" class="dice">
</div>
<script type='text/javascript' src="challenges.js"></script>
</body>
</html>
/**********************************************
*** GENERAL
**********************************************/
.final-score {
position: absolute;
left: 50%;
transform: translateX(-50%);
top: 520px;
color: #555;
font-size: 18px;
font-family: 'Lato';
text-align: center;
padding: 10px;
width: 160px;
text-transform: uppercase;
}
.final-score:focus { outline: none; }
dice-1 { top: 120px; }
#dice-2 { top: 250px; }
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.clearfix::after {
content: "";
display: table;
clear: both;
}
body {
background-image: linear-gradient(rgba(62, 20, 20, 0.4), rgba(62, 20, 20, 0.4)), url(back.jpg);
background-size: cover;
background-position: center;
font-family: Lato;
font-weight: 300;
position: relative;
height: 100vh;
color: #555;
}
.wrapper {
width: 1000px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: #fff;
box-shadow: 0px 10px 50px rgba(0, 0, 0, 0.3);
overflow: hidden;
}
.player-0-panel,
.player-1-panel {
width: 50%;
float: left;
height: 600px;
padding: 100px;
}
/**********************************************
*** PLAYERS
**********************************************/
.player-name {
font-size: 40px;
text-align: center;
text-transform: uppercase;
letter-spacing: 2px;
font-weight: 100;
margin-top: 20px;
margin-bottom: 10px;
position: relative;
}
.player-score {
text-align: center;
font-size: 80px;
font-weight: 100;
color: #EB4D4D;
margin-bottom: 130px;
}
.active { background-color: #f7f7f7; }
.active .player-name { font-weight: 300; }
.active .player-name::after {
content: "\2022";
font-size: 47px;
position: absolute;
color: #EB4D4D;
top: -7px;
right: 10px;
}
.player-current-box {
background-color: #EB4D4D;
color: #fff;
width: 40%;
margin: 0 auto;
padding: 12px;
text-align: center;
}
.player-current-label {
text-transform: uppercase;
margin-bottom: 10px;
font-size: 12px;
color: #222;
}
.player-current-score {
font-size: 30px;
}
button {
position: absolute;
width: 200px;
left: 50%;
transform: translateX(-50%);
color: #555;
background: none;
border: none;
font-family: Lato;
font-size: 20px;
text-transform: uppercase;
cursor: pointer;
font-weight: 300;
transition: background-color 0.3s, color 0.3s;
}
button:hover { font-weight: 600; }
button:hover i { margin-right: 20px; }
button:focus {
outline: none;
}
i {
color: #EB4D4D;
display: inline-block;
margin-right: 15px;
font-size: 32px;
line-height: 1;
vertical-align: text-top;
margin-top: -4px;
transition: margin 0.3s;
}
.btn-new { top: 45px;}
.btn-roll { top: 403px;}
.btn-hold { top: 467px;}
.dice {
position: absolute;
left: 50%;
top: 178px;
transform: translateX(-50%);
height: 100px;
box-shadow: 0px 10px 60px rgba(0, 0, 0, 0.10);
}
.winner { background-color: #f7f7f7; }
.winner .player-name { font-weight: 300; color: #EB4D4D; }
Please help me.
İn javascript , remove init(); or define init function.
try this:
function init() {
scores = [0, 0];
activePlayer = 0;
roundScore = 0;
gamePlaying = true;
document.getElementById('dice-1').style.display = 'none';
document.getElementById('dice-2').style.display = 'none';
document.getElementById('score-0').textContent = '0';
document.getElementById('score-1').textContent = '0';
document.getElementById('current-0').textContent = '0';
document.getElementById('current-1').textContent = '0';
document.getElementById('name-0').textContent = 'Player 1';
document.getElementById('name-1').textContent = 'Player 2';
document.querySelector('.player-0-panel').classList.remove('winner');
document.querySelector('.player-1-panel').classList.remove('winner');
document.querySelector('.player-0-panel').classList.remove('active');
document.querySelector('.player-1-panel').classList.remove('active');
document.querySelector('.player-0-panel').classList.add('active');
}
document.querySelector('.btn-roll').addEventListener('click', function() {
if(gamePlaying) {
var dice1 = Math.floor(Math.random() * 6) + 1;
var dice2 = Math.floor(Math.random() * 6) + 1;
document.getElementById('dice-1').style.display = 'block';
document.getElementById('dice-2').style.display = 'block';
document.getElementById('dice-1').src = 'dice-' + dice1 + '.png';
document.getElementById('dice-2').src = 'dice-' + dice2 + '.png';
if (dice1 !== 1 && dice2 !== 1) {
roundScore += dice1 + dice2;
document.querySelector('#current-' + activePlayer).textContent = roundScore;
} else {
nextPlayer();
}
}
});
document.querySelector('.btn-hold').addEventListener('click', function() {
if (gamePlaying) {
scores[activePlayer] += roundScore;
document.querySelector('#score-' + activePlayer).textContent = scores[activePlayer];
var input = document.querySelector('.final-score').value;
var winningScore;
if(input) {
winningScore = input;
} else {
winningScore = 100;
}
// Check if player won the game
if (scores[activePlayer] >= winningScore) {
document.querySelector('#name-' + activePlayer).textContent = 'Winner!';
document.getElementById('dice-1').style.display = 'none';
document.getElementById('dice-2').style.display = 'none';
document.querySelector('.player-' + activePlayer + '-panel').classList.add('winner');
document.querySelector('.player-' + activePlayer + '-panel').classList.remove('active');
gamePlaying = false;
} else {
nextPlayer();
}
}
});
function nextPlayer() {
activePlayer === 0 ? activePlayer = 1 : activePlayer = 0;
roundScore = 0;
document.getElementById('current-0').textContent = '0';
document.getElementById('current-1').textContent = '0';
document.querySelector('.player-0-panel').classList.toggle('active');
document.querySelector('.player-1-panel').classList.toggle('active');
document.getElementById('dice-1').style.display = 'none';
document.getElementById('dice-2').style.display = 'none';
}
document.querySelector('.btn-new').addEventListener('click', init);
function init(){
}
I don't see any HTML elements with id="dice-1" nor id="dice-2", which would explain the error you're receiving.
I don't see element with id="dice-1" or id="dice-2" in your template (HTML), so the error just means, that element with that id doesn't exist, so it's value is null.

localStorage cant save information

I'm trying to fix this error but if i fix have another error with
var save_button = document.getElementById('overlayBtn');
if(save_button){
save_button.addEventListener('click', updateOutput);}
i got next error
main.js:297 Uncaught TypeError: Cannot set property 'textContent' of null
//local storage savebtn
var note_textarea = document.querySelector('#TE');
var result_textarea = document.querySelector('#result');
var save_button = document.getElementById('SaveBtn');
var display = document.querySelector('#display');
var bell = document.getElementById('notification');
var save_button = document.getElementById('overlayBtn');
if(save_button){
save_button.addEventListener('click', updateOutput);}
result_textarea.textContent = localStorage.getItem('content_result');
note_textarea.textContent = localStorage.getItem('content_textarea');
display.value = localStorage.getItem('content_display');
bell.textContent = localStorage.getItem('bell_count');
function updateOutput() {
Notiflix.Notify.Success('Text has been saved ');
localStorage.setItem('content_textarea', note_textarea.value);
localStorage.setItem('content_result', result_textarea.value);
localStorage.setItem('content_display', display.value);
localStorage.setItem('bell_count', bell.textContent);
}
This is code i have problem with (up)
I only want to get after press savebutton all content save.
FULL CODE
function myFunction() {
var x = document.getElementById("Cal");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
var queue = []; // store key history
function getHistory() {
var str = ''
for (var i = 0; i < queue.length; i++)
str += queue[i];
return str;
}
// display functions
function runLB() {
document.case.display.value += "("
queue.push('(')
}
function runRB() {
document.case.display.value += ")"
queue.push(')')
}
function run1() {
document.case.display.value += "1"
queue.push('1')
};
function run2() {
document.case.display.value += "2"
queue.push('2')
};
function run3() {
document.case.display.value += "3"
queue.push('3')
};
function run4() {
document.case.display.value += "4"
queue.push('4')
};
function run5() {
document.case.display.value += "5"
queue.push('5')
};
function run6() {
document.case.display.value += "6"
queue.push('6')
};
function run7() {
document.case.display.value += "7"
queue.push('7')
};
function run8() {
document.case.display.value += "8"
queue.push('8')
};
function run9() {
document.case.display.value += "9"
queue.push('9')
};
function run0() {
document.case.display.value += "0"
queue.push('0')
};
function runPlus() {
document.case.display.value += "+"
queue.push('+')
};
function runMinus() {
document.case.display.value += "-"
queue.push('-')
};
function runDivide() {
document.case.display.value += "/"
queue.push('/')
};
function runMultiply() {
document.case.display.value += "*"
queue.push('*')
};
function runComma() {
document.case.display.value += "."
queue.push('.')
};
function runBack() {
var val = document.case.display.value.slice(0, -1);
document.case.display.value = val;
if (queue.length > 1) {
// pop last element from the array
let last = queue.pop();
// check if element length is more than 1
if (last.length > 1) {
// remove last character from string and push to the array again
queue.push(last.slice(0, -1))
}
}
};
function testLength() {
if (document.case.display.value.length > 16 && document.case.display.value.length < 21) {
document.getElementById("display").style.fontWeight = "550";
document.getElementById("display").style.fontSize = "2em";
} else if (document.case.display.value.length == 16 || document.case.display.value.length == 21) {
Notiflix.Notify.Info('Because you have a lot of charatchers font size is smaller');
} else if (document.case.display.value.length > 25) {
var str = document.case.display.value.length
Notiflix.Notify.Warning('Max characters you can see is 28 ');
Notiflix.Notify.Failure('Number of your characters' + str);
document.getElementById("display").style.fontWeight = "500";
document.getElementById("display").style.fontSize = "1.5em";
} else {
document.getElementById("display").style.fontWeight = "500";
document.getElementById("display").style.fontSize = "2.5em";
}
}
document.addEventListener("DOMContentLoaded", function(event) {
var numbers = document.querySelectorAll(".digit, #back")
numbers.forEach(el => el.addEventListener('click', testLength))
});
function runEquals() {
if (document.case.display.value.length < 3) {
Notiflix.Notify.Info('Enter charatchers !');
countBell();
} else if (isNaN(document.case.display.value)) {
var equals = Math.round(eval(document.case.display.value) * 1000) / 1000;
document.case.display.value = equals;
document.getElementById("result").innerHTML += queue.join("") + "=" + equals + "\n";
queue = [equals.toString()];
document.getElementById('back').value = "CE";
document.getElementById('back').onclick = runBack;
Notiflix.Notify.Success('Success');
} else if (document.case.display.value == "Infinity") {
document.getElementById('back').value = "AC";
document.getElementById('back').onclick = DeleteAll;
Notiflix.Notify.Warning(' Infinity ! ');
countBell();
} else {
document.getElementById('back').value = "CE";
document.getElementById('back').onclick = runBack;
Notiflix.Notify.Warning(' Can not be calculated ! ');
countBell();
}
}
function testNum() {
if (document.case.display.value == "Infinity") {
document.getElementById('back').value = "AC";
document.getElementById('back').onclick = DeleteAll;
Notiflix.Notify.Warning(' Infinity ! ');
countBell();
} else if (document.case.display.value == "NaN") {
document.getElementById('back').value = "AC";
document.getElementById('back').onclick = DeleteAll;
Notiflix.Notify.Warning(' Not a Number ! ');
countBell();
} else if (!document.case.display.value.includes("")) {} else if (document.case.display.value.includes("/0")) {
Notiflix.Notify.Failure(' You cannot divide by 0 ! ');
countBell();
} else if (document.case.display.value.includes("..") || document.case.display.value.includes("//") || document.case.display.value.includes("**") || document.case.display.value.includes("--") || document.case.display.value.includes("++")) {
runBack();
Notiflix.Notify.Failure('Enter number ! ');
countBell();
} else if (!document.case.display.value.includes("(") && document.case.display.value.includes(")")) {
Notiflix.Notify.Failure('U cannot end bracket now !');
countBell();
} else if (document.case.display.value.includes(")") && !/([123456789])/.test(document.case.display.value)) {
Notiflix.Notify.Failure('U cannot end bracket now !');
countBell();
} else if (document.case.display.value.includes(")") && !/([+/*-])/.test(document.case.display.value)) {
Notiflix.Notify.Failure('U cannot end bracket now !');
countBell();
} else if (!document.case.display.value.includes("(") && document.case.display.value.includes(")") && !/([+/*-])/.test(document.case.display.value)) {
Notiflix.Notify.Failure('U cannot end bracket now !');
countBell();
} else if (!document.case.display.value.includes("(") && document.case.display.value.includes(")") && !/([+/*-])/.test(document.case.display.value) && !/([123456789])/.test(document.case.display.value)) {} else {
document.getElementById('back').value = "CE";
document.getElementById('back').onclick = runBack;
}
}
document.addEventListener("DOMContentLoaded", function(event) {
var numbers = document.querySelectorAll(".digit, .oper")
numbers.forEach(el => el.addEventListener('click', testNum))
});
Notiflix.Confirm.Init({
timeout: 3000,
okButtonBackground: "#C46600",
titleColor: "#C46600",
});
function DeleteAll() {
document.case.display.value = "";
}
function Del() {
Notiflix.Confirm.Show(' Confirm',
'Are you sure you want to delete text?', 'Yes', 'No',
function() {
Notiflix.Notify.Success('Text is Deleted');
document.getElementById("result").innerHTML = "";
},
function() {
Notiflix.Notify.Info('Text is not Deleted');
countBell();
});
}
//print
function printTextArea() {
childWindow = window.open('', 'childWindow', 'location=yes, menubar=yes, toolbar=yes');
childWindow.document.open();
childWindow.document.write('<html><head></head><body>');
childWindow.document.write(document.getElementById('result').value.replace(/\n/gi, '<br>'));
childWindow.document.write('</body></html>');
childWindow.print();
childWindow.document.close();
childWindow.close();
}
//Font ++ and --
function FontM() {
txt = document.getElementById('result');
style = window.getComputedStyle(txt, null).getPropertyValue('font-size');
currentSize = parseFloat(style);
if (currentSize <= 10) {
txt.style.fontSize = (currentSize + 5) + 'px';
Notiflix.Notify.Info('Smallest font size');
} else {
txt.style.fontSize = (currentSize - 5) + 'px';
Notiflix.Notify.Info('Font size -5px');
}
}
//print
function FontP() {
txt = document.getElementById('result');
style = window.getComputedStyle(txt, null).getPropertyValue('font-size');
currentSize = parseFloat(style);
if (currentSize >= 50) {
txt.style.fontSize = (currentSize - 5) + 'px';
Notiflix.Notify.Info('Biggest font size');
} else {
txt.style.fontSize = (currentSize + 5) + 'px';
Notiflix.Notify.Info('Font size +5px');
}
}
//local storage savebtn
var note_textarea = document.querySelector('#TE');
var result_textarea = document.querySelector('#result');
var save_button = document.getElementById('SaveBtn');
var display = document.querySelector('#display');
var bell = document.getElementById('notification');
var save_button = document.getElementById('overlayBtn');
if(save_button){
save_button.addEventListener('click', updateOutput);
}
result_textarea.textContent = localStorage.getItem('content_result');
note_textarea.textContent = localStorage.getItem('content_textarea');
display.value = localStorage.getItem('content_display');
bell.textContent = localStorage.getItem('bell_count');
function updateOutput() {
Notiflix.Notify.Success('Text has been saved ');
localStorage.setItem('content_textarea', note_textarea.value);
localStorage.setItem('content_result', result_textarea.value);
localStorage.setItem('content_display', display.value);
localStorage.setItem('bell_count', bell.textContent);
}
window.onload = function() {
const myInput = document.getElementById('display');
myInput.onpaste = function(e) {
e.preventDefault();
}
}
function Git() {
window.open("https://github.com/TheLexa", "_blank");
countBell()
};
var count = 0;
function countBell() {
setTimeout(function(){
document.getElementById('notification').innerText = '🔔';
document.getElementById('notification').style.fontSize = '25px';
setTimeout(function(){
document.getElementById('notification').innerText = x;
document.getElementById('notification').style.fontSize = '33px';
setTimeout(function(){
document.getElementById('notification').innerText = '🔔' + x;
document.getElementById('notification').style.fontSize = '22px';
}, 2000);
}, 3000);
}, 2000);
document.getElementById('notification').style.border = "thick solid red ";
count += 1;
notifNote();
}
var x = -1;
function notifNote() {
x++;
if(x==0){
}else{
localStorage.setItem('display_notification' + x, display.value);
localStorage.setItem('x' ,x);
}
}
window.onload = function() {
countBell();
x =+ localStorage.getItem('x');
}
function notif() {
Notiflix.Confirm.Show('Answer', 'Do you want to delete' + ' ' + '(' + x + ')' + ' ' + 'notification', 'Show Notification', 'Yes Delete Notification',
function() {
Notiflix.Report.Success(
' Success', 'We put notification in Note', 'Click');
var note_textarea = document.querySelector('#TE');
var y = 0;
if (x == 0) {
Notiflix.Report.Warning('INFO', 'No notification', 'Click');
} else {
for (y = 1; x > y; y++) {
note_textarea.textContent += '\n' + localStorage.getItem('display_notification' + y) + ' ' + 'Cannot be calculated';
}
note_textarea.textContent += '\n' + localStorage.getItem('display_notification' + y) + ' ' + 'Cannot be calculated';
}
},
function() {
count = 1;
setTimeout(function(){
document.getElementById('notification').innerText = '🔔';
document.getElementById('notification').style.fontSize = '25px';
setTimeout(function(){
document.getElementById('notification').innerText = '0';
document.getElementById('notification').style.fontSize = '33px';
setTimeout(function(){
document.getElementById('notification').innerText = '🔔';
document.getElementById('notification').style.fontSize = '22px';
}, 2000);
}, 1000);
}, 2000);
var z;
for (z = 0; x > z; z++) {
localStorage.removeItem('display_notification' + z);
}
localStorage.removeItem('display_notification' + z);
x = 0;
Notiflix.Report.Success(
' Success', 'Notification success deleted', 'Click');
});
};
// NUMBERS
/*
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if ( (charCode < 40 || charCode > 57)) {
return false;
}
return true;
}
var equal = document.getElementById("equal");
wage.addEventListener("keydown", function (e) {
if (e.keyCode === 13) { //checks whether the pressed key is "Enter"
runEquals();
}
});
*/
#media only screen and (max-width: 600px) {
body {
background-color: lightblue;
}
}
#wrapper {
display: flex;
}
html {
background:
linear-gradient(rgba(196, 102, 0, 0.6), rgba(155, 89, 182, 0.6));
}
ul {
list-style: none;
}
body {
width: 500px;
overflow: hidden;
}
#Print {
border: 1px solid rgba(255, 110, 0, 0.7);
margin-left: 85px;
position: absolute;
color: white;
background: rgba(196, 102, 0, 0.6);
font-size: 19px;
width: 85px;
height: 30px;
font-family: sans-serif;
text-decoration: none;
box-sizing: border-box;
background-size: 400%;
}
#Del {
border: 1px solid rgba(255, 110, 0, 0.7);
margin-left: 5px;
position: absolute;
color: white;
background: rgba(196, 102, 0, 0.6);
font-size: 19px;
width: 80px;
height: 30px;
font-family: sans-serif;
text-decoration: none;
box-sizing: border-box;
background-size: 400%;
border-radius: 1px;
}
#Git {
position: absolute;
color: #fff;
background: rgba(255, 110, 0, 0.5);
left: 94.5%;
font-size: 20px;
border-radius: 30px;
width: 80px;
height: 60px;
font-family: sans-serif;
text-decoration: none;
box-sizing: border-box;
background-size: 400%;
border: 2px solid rgba(255, 110, 0, 0.1);
}
#Note {
border: 3px solid rgba(155, 89, 182, 1);
margin-bottom: 25px;
transform: translate(0, 50%);
width: 401px;
height: 50px;
color: #fff;
font-family: 'Inconsolata', monospace;
font-size: 25px;
text-transform: uppercase;
text-decoration: none;
font-family: sans-serif;
box-sizing: border-box;
background: rgba(155, 89, 182, 1);
background-size: 400%;
border-radius: 0px 0px 7px 7px;
z-index: 1;
}
#Note:hover {
animation: animate 5s linear infinite;
}
#keyframes animate {
0% {
background-position: 0%;
}
100% {
background-position: 500%;
}
}
#Note:before {
content: '';
position: absolute;
top: -5px;
left: -5px;
right: -5px;
bottom: -5px;
z-index: -1;
background: linear-gradient(90deg, #03a9f4, #f441a5, #ffeb3b, #03a9f4);
background-size: 400%;
border-radius: 40px;
opacity: 0;
transition: 0.5s;
}
#Note:hover:before {
filter: blur(20px);
opacity: 1;
animation: animate 5s linear infinite;
}
{}
form {
background: linear-gradient(rgba(196, 102, 0, 0.6), rgba(155, 89, 182, 0.6));
text-align: center;
align-content: center;
border-radius: 10px;
border: 3px solid rgba(196, 102, 0, 0.6);
}
#display {
font-family: 'Roboto', sans-serif;
width: 98%;
height: 60px;
text-align: right;
margin: 5px;
border: 5px solid rgba(196, 102, 0, 0.9);
font-size: 2.5em;
font-weight: 500px;
}
.digit {
font-size: 2rem;
background-color: #f8f8f8;
height: 55px;
width: 22%;
border: 1px solid #c6c6c6;
display: inline-block;
box-shadow: 1px 1px 1px;
color: #222;
font-family: Roboto-Regular, helvetica, arial, sans-serif;
margin: 1.5px;
opacity: 0.9;
box-shadow: 0 1px 1px rgba(0, 0, 0, .1)
}
.oper {
font-size: 2rem;
background-color: #d6d6d6;
height: 55px;
width: 22%;
color: #444;
display: inline-block;
margin: 1.5px;
box-shadow: 0 1px 1px;
font-family: Roboto-Regular, helvetica, arial, sans-serif;
opacity: 0.9;
border: 1px solid #b6b6b6;
box-shadow: 0 1px 1px rgba(0, 0, 0, .1)
}
#equal {
background-color: rgba(196, 102, 0, 0.6);
color: white;
width: 183px;
border: none;
}
#TE {
display: block;
resize: none;
width: 386px;
height: 300px;
margin-top: 5px;
margin-left: 7px;
font-size: 20px;
border: 1px solid rgba(196, 102, 0, 0.9);
border-radius: 0px 0px 10px 10px;
font-family: 'Inconsolata', monospace;
}
#result {
margin-left: 5px;
display: block;
resize: none;
width: 400px;
height: 430px;
max-width: 400px;
max-height: 600px;
font-size: 20px;
border-radius: 10px 10px 1px 1px;
border: 1px solid rgba(196, 102, 0, 0.9);
}
button, input[type=button] {
cursor: pointer;
}
.digit:hover, .oper:hover {
border: 1px solid rgba(0, 0, 0, .1);
box-shadow: 0px 1px 1px rgba(0, 0, 0, .1);
opacity: 1;
}
#Del:hover, #Print:hover, #Git:hover, #FP:hover, #FM:hover, #SaveBtn:hover {
opacity: 0.8;
font-size: 20px;
}
#display:hover {
border: 4px solid rgba(196, 102, 0, 0.9);
}
#FP {
border: 1px solid rgba(255, 110, 0, 0.7);
margin-left: 170px;
position: absolute;
color: white;
background: rgba(196, 102, 0, 0.6);
font-size: 19px;
width: 80px;
height: 30px;
font-family: sans-serif;
text-decoration: none;
box-sizing: border-box;
background-size: 400%;
border-radius: 1px;
}
#FM {
border: 1px solid rgba(255, 110, 0, 0.7);
margin-left: 250px;
position: absolute;
color: white;
background: rgba(196, 102, 0, 0.6);
font-size: 19px;
width: 80px;
height: 30px;
font-family: sans-serif;
text-decoration: none;
box-sizing: border-box;
background-size: 400%;
border-radius: 1px;
}
#SaveBtn {
border: 1px solid rgba(255, 110, 0, 0.7);
background: rgba(200, 102, 0, 0.75);
margin-left: 330px;
position: absolute;
color: white;
font-size: 21px;
width: 75px;
height: 30px;
font-family: sans-serif;
text-decoration: none;
box-sizing: border-box;
background-size: 400%;
border-radius: 1px;
border-radius: 0px 0px 10px 0px;
}
#notification {
border: 3px solid rgba(155, 89, 182, 1);
background: white;
margin-left: 1470px;
margin-top: 730px;
position: absolute;
color: black;
font-size: 22px;
width: 56.5px;
height: 56.5px;
font-family: sans-serif;
text-decoration: none;
box-sizing: border-box;
background-size: 400%;
border-radius: 1px;
border-radius: 60px 60px 60px 60px;
animation-name: example;
animation-duration: 30s;
}
#keyframes example {
0% {
border-color: red;
}
5% {
border-color: yellow;
}
10% {
border-color: blue;
}
15% {
border-color: green;
}
20% {
border-color: red;
}
25% {
border-color: yellow;
}
30% {
border-color: blue;
}
35% {
border-color: green;
}
40% {
border-color: red;
}
45% {
border-color: yellow;
}
50% {
border-color: blue;
}
55% {
border-color: green;
}
60% {
border-color: red;
}
65% {
border-color: yellow;
}
70% {
border-color: blue;
}
75% {
border-color: green;
}
80% {
border-color: red;
}
85% {
border-color: yellow;
}
90% {
border-color: blue;
}
95% {
border-color: green;
}
100% {
border-color: red;
}
}
<html>
<head>
<!--Copyright 2019, Aleksa Kovacevic, All rights reserved.-->
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="Online calculators for everything. Some solve problems, some satisfy curiosity." />
<meta name="keywords" content="calculator, mortgage, loan,lease, cooking, math, college tuition, agriculture, finance,fractions,love,scientific, design, health, unit converter, pocket, running, calculators" />
<link rel="icon" href="https://www.apkmirror.com/wp-content/uploads/2017/11/5a0aad10ea5ec.png">
<title id="Title">Calculator </title>
<link href="https://fonts.googleapis.com/css?family=Inconsolata&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
<link rel="stylesheet" href="main.css" type="text/css">
<link rel="stylesheet" href="Notiflix\node_modules\notiflix\dist\notiflix-1.8.0.min.css" />
<script src="Notiflix\node_modules\notiflix\dist\notiflix-aio-1.8.0.js""></script>
<script src=" main.js" type="text/javascript"></script>
</head>
<body>
<button type="button" id="notification" onclick="notif()"> 🔔</button>
<button type="button" id="Git" onclick="Git()"> GitHub</button>
<div id="wrapper">
<form name="case">
<!--Buttons -->
<input name="display" id="display" placeholder "0" onkeypress="" autofocus readonly>
<input type="button" class="oper" value="(" onclick="runLB()">
<input type="button" class="oper" value=")" onclick="runRB()">
<input type="button" id="back" class="oper" value="CE" onclick="runBack()">
<input type="button" id="divide" class="oper" value="÷" onclick="runDivide()">
<input type="button" class="digit" value="1" onclick="run1()">
<input type="button" class="digit" value="2" onclick="run2()">
<input type="button" class="digit" value="3" onclick="run3()">
<input type="button" id="multiply" class="oper" value="×" onclick="runMultiply()">
<input type="button" class="digit" value="4" onclick="run4()">
<input type="button" class="digit" value="5" onclick="run5()">
<input type="button" class="digit" value="6" onclick="run6()">
<input type="button" id="minus" class="oper" value="-" onclick="runMinus()">
<input type="button" class="digit" value="7" onclick="run7()">
<input type="button" class="digit" value="8" onclick="run8()">
<input type="button" class="digit" value="9" onclick="run9()">
<input type="button" id="plus" class="oper" value="+" onclick="runPlus()">
<input type="button" class="digit" value="0" onclick="run0()">
<input type="button" id="comma" class="digit" value="." onclick="runComma()">
<input type="button" id="equal" class="oper" value="=" onclick="runEquals()">
<div id="Cal">
<textarea id="TE" placeholder="Note"></textarea>
</div>
<div id="newpos">
<!-- button rainbow -->
<button type="button" id="Note" onclick="myFunction()"> Note</button></div>
</form>
<div id="new">
<!--result textarea-->
<textarea id="result" placeholder="History" readonly></textarea>
<button type="button" id="Del" onclick="Del()"> Delete</button>
<button type="button" id="Print" onclick="printTextArea()"> Print</button>
<button type="button" id="FP" onclick="FontP()">Font +</button>
<button type="button" id="FM" onclick="FontM()">Font -</button>
<button type="button" id="SaveBtn"> Save </button>
</div>
</div>
</body>
NOTIFLIX IS library for client-side non-blocking notifications, popup boxes, loading indicators, and more to that makes your web projects much better.
THIS is my portofolio if you have any good information tell me THANKS :)
The problem here is the dom is not loaded so the textarea is not available until the dom is not loaded. adding a window load listener for it will solve it.
window.addEventListener('load', function(){
//local storage savebtn
var note_textarea = document.querySelector('#TE');
var result_textarea = document.querySelector('#result');
var save_button = document.getElementById('SaveBtn');
var display = document.querySelector('#display');
var bell = document.getElementById('notification');
var save_button = document.getElementById('overlayBtn');
if(save_button){
save_button.addEventListener('click', updateOutput);
}
result_textarea.textContent = localStorage.getItem('content_result');
note_textarea.textContent = localStorage.getItem('content_textarea');
display.value = localStorage.getItem('content_display');
bell.textContent = localStorage.getItem('bell_count');
})
The function does not see the bell variable because a javascript scope does not allow it to be seen. You need to get your dom elements in the inside of the updateOutput function.
function updateOutput() {
var note_textarea = document.querySelector('#TE');
var result_textarea = document.querySelector('#result');
var save_button = document.getElementById('SaveBtn');
var display = document.querySelector('#display');
var bell = document.getElementById('notification');
Notiflix.Notify.Success('Text has been saved ');
localStorage.setItem('content_textarea', note_textarea.value);
localStorage.setItem('content_result', result_textarea.value);
localStorage.setItem('content_display', display.value);
localStorage.setItem('bell_count', bell.textContent);
}

Move Div Only With JS HTML CSS [Need to Improve the code and possibly shorten it]

I built this code and I want to improve it and maybe shorten it a little bit. I thought maybe replace the switch in Shorten IF and it did not work.
I would be happy to help thanks.
let positionL = 200;
let positionT = 200;
function moveDiv(e) {
var div = document.getElementById("Circle").style;
switch (e) {
case "left":
div.background = "blue";
positionL -= 5;
if (positionL <= 55) {
div.background = "red";
positionL = 55;
}
div.left = positionL + "px"; // left
break;
case "up":
div.background = "blue";
positionT -= 5;
if (positionT <= 55) {
div.background = "red";
positionT = 55;
}
div.top = positionT + "px"; // up
break;
case "right":
div.background = "blue";
positionL += 5;
if (positionL >= 345) {
div.background = "red";
positionL = 345;
}
div.left = positionL + "px"; // right
break;
case "down":
div.background = "blue";
positionT += 5;
if (positionT >= 345) {
div.background = "red";
positionT = 345;
}
div.top = positionT + "px"; // down
break;
case "reset":
positionL = 200;
positionT = 200;
div.background = "blue";
div.left = positionL + "px";
div.top = positionT + "px";
break;
default:
return;
}
}
.Continer {
display: flex;
justify-content: start;
left: 400px;
top: 400px;
}
#Divcontainer {
width: 400px;
height: 400px;
position: relative;
border: solid;
}
#Circle {
width: 100px;
height: 100px;
position: absolute;
background-color: blue;
border-radius: 50%;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
.Controller {
width: 100px;
height: 400px;
position: relative;
border: solid;
margin: 0 0 0 2px;
text-align: center;
}
button {
padding: 8px 16px;
margin-top: 30px;
}
<div class="Continer">
<div id="Divcontainer">
<div id="Circle"></div>
</div>
<div class="Controller">
<button onclick="moveDiv('up')">^</button><br /><br />
<button onclick="moveDiv('left')">
<
</button>
<button onclick="moveDiv('right')">></button><br /><br />
<button onclick="moveDiv('down')">v</button>
<button onclick="moveDiv('reset')">reset</button>
</div>
</div>
Cleaned up your JS a bit:
let positionL = 200;
let positionT = 200;
let bounds = {
left: 55,
top: 55,
right: 345,
bottom: 345
};
function moveDiv(e) {
if (e === "reset") {
positionL = 200;
positionT = 200;
} else {
// this implementation will be advantageous when you start using keyboard inputs
// and multiple directions can be pressed at the same time; even contradicting ones
// like left AND right
positionL += 5 * ((e === "right") - (e === "left"));
positionT += 5 * ((e === "down") - (e === "up"));
}
var red = positionL <= bounds.left ||
positionL >= bounds.right ||
positionT <= bounds.top ||
positionT >= bounds.bottom;
positionL = Math.max(bounds.left, Math.min(bounds.right, positionL));
positionT = Math.max(bounds.top, Math.min(bounds.bottom, positionT));
var div = document.getElementById("Circle").style;
div.left = positionL + "px";
div.top = positionT + "px";
div.background = red ? "red" : "blue";
}
.Continer {
display: flex;
justify-content: start;
left: 400px;
top: 400px;
}
#Divcontainer {
width: 400px;
height: 400px;
position: relative;
border: solid;
}
#Circle {
width: 100px;
height: 100px;
position: absolute;
background-color: blue;
border-radius: 50%;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
transition: all ease-in 150ms;
}
.Controller {
width: 100px;
height: 400px;
position: relative;
border: solid;
margin: 0 0 0 2px;
text-align: center;
}
button {
padding: 8px 16px;
margin-top: 30px;
}
<div class="Continer">
<div id="Divcontainer">
<div id="Circle"></div>
</div>
<div class="Controller">
<button onclick="moveDiv('up')">^</button><br /><br />
<button onclick="moveDiv('left')"><</button>
<button onclick="moveDiv('right')">></button><br /><br />
<button onclick="moveDiv('down')">v</button>
<button onclick="moveDiv('reset')">reset</button>
</div>
</div>

Categories

Resources