I want to clear km and persons and I tried it in different ways like
inp1 = null, inp1 = isNaN, inp1 = "" (the same with inp2) and with appending innerHTML and or .value on the end and further the same with km and persons but none of these methods worked. The clearing should happen after several seconds like I described in my sub- function "clear" which is a parameter of the setTimeOut function. The clear() function should happen when someone is inserting a number over four in the persons field
<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>Document</title>
<script>
function calci() {
const {routePrice, km, persons, output} = VarOfElements();
const condExceededPersons = persons > 4;
const condPersonsCosts = persons === 4 && km > 0;
const condNonePersonsCosts = persons < 4 || !isNaN(persons);
if (condExceededPersons) {
output.innerHTML = "Only four persons can drive with you!";
setTimeout(clear,3500);
function clear() {
output.innerHTML = "Please enter adequate informations";
km = null
persons = null
}
return; /*the above area is to considering and the function under the calci function in which the elements are declared*/
} else if (condPersonsCosts) {
var personsExpenses = 5;
} else if (condNonePersonsCosts) {
personsExpenses = 0;
}
const noInput = isNaN(km);
if (noInput) {
output.innerHTML = "Please enter a distance";
return;
}
const conditionSevenO = km <= 7 && km > 0;
const overSevenOeq = km > 7 && km > 0;
if (conditionSevenO) {
y = 3.9
var wholeExpenses = routePrice * km + y + personsExpenses;
output.innerHTML = "You have to pay " + wholeExpenses.toFixed(2) + "โฌ";
} else if (overSevenOeq) {
y = 3.9
let sevenLess = km - 7;
let overSevenRoute = 1.65;
let overSeven = sevenLess * overSevenRoute;
let seventhExpenses = 16.10;
wholeExpenses = y + seventhExpenses + overSeven + personsExpenses;
output.innerHTML = "You have to pay " + wholeExpenses.toFixed(2) + "โฌ";
}
}
function VarOfElements() {
var routePrice = 2.3;
const inp1 = document.getElementById('input-box1');
const inp2 = document.getElementById('input-box2');
const km = parseInt(inp1.value);
var persons = parseInt(inp2.value);
output = document.getElementById('output-box');
return {routePrice, km, persons, output, inp1,inp2};
};
</script>
</head>
<style>
.body {
display: flex;
justify-content: center;
font-family: 'Padauk', sans-serif;
}
#heading {
color: rgba(130, 195, 236, 1);
}
#boxes {
display: flex;
justify-content: space-between;
flex-direction: column;
align-items: center;
padding: 20vh;
align-items: center;
gap: 30px;
}
#input-box1:focus, #input-box2:focus {
border: none;
box-shadow: rgb(10, 126, 179) 0 0 10px ;
}
#boxes>*:nth-child(4) {
margin-top: 1vh;
}
#boxes>*:nth-child(5) {
margin-top:-1vh;
}
.input {
background-color: rgba(152, 187, 209, 0.386);
border: 1px solid;
border-radius: 5px;
border-color: rgba(130, 195, 236, 1);
}
.box {
width: 32vh;
height: 5vh;
text-align: center;
}
#output-box {
border: 1px solid;
border-radius: 30px;
border-color: rgb(10, 126, 179);
background-color: rgba(64, 143, 193, 0.453);
color: rgba(29, 2, 54, 0.311);
line-height:40px;
text-align: center;
box-shadow: blueviolet 0 0 10px;
}
::placeholder {
color: rgba(0, 0, 0, 0.232);
}
#button {
border: 1px solid;
border-radius: 5px;
background-color: rgba(152, 187, 209, 0.386);
border-color: rgba(130, 195, 236, 1);
color: rgba(52, 160, 228, 0.588);
box-shadow: 0 0 10px rgba(130, 195, 236, 1);
cursor: pointer;
}
#button:hover {
color: white;
}
</style>
<body>
<div id="boxes">
<h1 id="heading"> Taximeter</h1>
<label class="labels" id="km" for="input-box1">km</label>
<input oninput="this.value = Math.abs(this.value)" min="0" placeholder="How far is your target?" id="input-box1"
class="box input" type="number">
<label class="labels" id="personen" for="input-box2"> Passengers </label>
<input min="0" max="4" oninput="this.value = Math.abs(this.value)" min="0"
placeholder="How many people are driving with you?" id="input-box2" class="box input" type="number">
<label class="labels" id="Preis" for="output-box">Price</label>
<output placeholder = "Please enter informations" class="box" id="output-box"></output>
<button onclick="calci()" id="button"> calculate!</button>
</div>
</div>
</body>
</html>
Answer edit because of the question in the comment section:
You could use the variables declared in the VarOfElements(), but it's not km and persons those who represents the actual value of your inputs. Instead, they are just variables that are equal to the value of your input elements.
What you actually need is the inp1 and inp2. Those variables indeed have your HTML <input> element's value and everything else, if you need.
So you can declare them in your const that gets the variables of your VarOfElements() function, and simply use them, just add .value to actually change it.
<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>Document</title>
<script>
function calci() {
const {routePrice, km, persons, output, inp1, inp2} = VarOfElements();
console.log(inp1);
const condExceededPersons = persons > 4;
const condPersonsCosts = persons === 4 && km > 0;
const condNonePersonsCosts = persons < 4 || !isNaN(persons);
if (condExceededPersons) {
output.innerHTML = "Only four persons can drive with you!";
setTimeout(clear,3500);
function clear() {
output.innerHTML = "Please enter adequate informations";
inp1.value = null;
inp2.value = null;
}
return; /*the above area is to considering and the function under the calci function in which are the elements are declared*/
} else if (condPersonsCosts) {
var personsExpenses = 5;
} else if (condNonePersonsCosts) {
personsExpenses = 0;
}
const noInput = isNaN(km);
if (noInput) {
output.innerHTML = "Please enter a distance";
return;
}
const conditionSevenO = km <= 7 && km > 0;
const overSevenOeq = km > 7 && km > 0;
if (conditionSevenO) {
y = 3.9
var wholeExpenses = routePrice * km + y + personsExpenses;
output.innerHTML = "You have to pay " + wholeExpenses.toFixed(2) + "โฌ";
} else if (overSevenOeq) {
y = 3.9
let sevenLess = km - 7;
let overSevenRoute = 1.65;
let overSeven = sevenLess * overSevenRoute;
let seventhExpenses = 16.10;
wholeExpenses = y + seventhExpenses + overSeven + personsExpenses;
output.innerHTML = "You have to pay " + wholeExpenses.toFixed(2) + "โฌ";
}
}
function VarOfElements() {
var routePrice = 2.3;
const inp1 = document.getElementById('input-box1');
const inp2 = document.getElementById('input-box2');
const km = parseInt(inp1.value);
var persons = parseInt(inp2.value);
output = document.getElementById('output-box');
return {routePrice, km, persons, output, inp1,inp2};
};
</script>
</head>
<style>
body, html {
overflow: hidden
}
.body {
display: flex;
justify-content: center;
font-family: 'Padauk', sans-serif;
}
#heading {
color: rgba(130, 195, 236, 1);
}
#boxes {
display: flex;
justify-content: space-between;
flex-direction: column;
align-items: center;
padding: 20vh;
align-items: center;
gap: 30px;
}
#input-box1:focus, #input-box2:focus {
border: none;
box-shadow: rgb(10, 126, 179) 0 0 10px ;
}
#boxes>*:nth-child(4) {
margin-top: 1vh;
}
#boxes>*:nth-child(5) {
margin-top:-1vh;
}
.input {
background-color: rgba(152, 187, 209, 0.386);
border: 1px solid;
border-radius: 5px;
border-color: rgba(130, 195, 236, 1);
}
.box {
width: 32vh;
height: 5vh;
text-align: center;
}
#output-box {
border: 1px solid;
border-radius: 30px;
border-color: rgb(10, 126, 179);
background-color: rgba(64, 143, 193, 0.453);
color: rgba(29, 2, 54, 0.311);
line-height:40px;
text-align: center;
box-shadow: blueviolet 0 0 10px;
}
::placeholder {
color: rgba(0, 0, 0, 0.232);
}
#button {
border: 1px solid;
border-radius: 5px;
background-color: rgba(152, 187, 209, 0.386);
border-color: rgba(130, 195, 236, 1);
color: rgba(52, 160, 228, 0.588);
box-shadow: 0 0 10px rgba(130, 195, 236, 1);
cursor: pointer;
}
#button:hover {
color: white;
}
</style>
<body>
<div id="boxes">
<h1 id="heading"> Taximeter</h1>
<label class="labels" id="km" for="input-box1">km</label>
<input oninput="this.value = Math.abs(this.value)" min="0" placeholder="How far is your target?" id="input-box1"
class="box input" type="number">
<label class="labels" id="personen" for="input-box2"> Passengers </label>
<input min="0" max="4" oninput="this.value = Math.abs(this.value)" min="0"
placeholder="How many people are driving with you?" id="input-box2" class="box input" type="number">
<label class="labels" id="Preis" for="output-box">Price</label>
<output placeholder = "Please enter informations" class="box" id="output-box"></output>
<button onclick="calci()" id="button"> calculate!</button>
</div>
</div>
</body>
</html>
Related
I am working on a prototype that can enable drag & drop actions between containers. However, I have a conflict case in this :
when I use position: absolute for the draggable items, they are draggable but they are on top of each other :/
when I use position: relative, they are distributed evenly in their container but they are not draggable :/
I collected the code in the below chuck to be testable; please let me know what you think how I can fix this.
<!DOCTYPE html>
<html>
<head>
<style>
html,
body {
width: 100%;
height: 100%;
overflow: hidden;
}
.lang1Container {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
justify-content: flex-start;
}
.meaningContainer {
border: 1px solid rgba(15, 15, 15, 0.2);
box-shadow: 0px 0px 5px 10px rgba(138, 57, 57, 0.2);
}
.lang1Item {
width: 300px;
height: 20px;
position: absolute;
background-color: #f44336;
color: #ffffff;
font-family: Oxygen, sans-serif;
font-size: px;
padding: 7px;
box-shadow: inset 1px 1px 10px 0 rgba(138, 57, 57, 0.2);
border-radius: 3px;
cursor: pointer;
}
.snap {
width: 301px;
height: 30px;
margin-top: 25px;
margin-bottom: 25px;
}
.over {
background-color: rgb(158, 89, 87, 0.2);
border: 1px solid #7c5b59;
border-radius: 3px;
border-style: dashed;
}
</style>
</head>
<body>
<div style="display: flex; flex-direction: column">
<div
id="lang1MeaningContainer"
style="
background-color: bisque;
min-width: 300px;
min-height: 400px;
border-color: red;
border-style: dashed;
margin: 10px;
"
>
<div class="header">lang1MeaningContainer - Meaning Container</div>
<div class="snap"></div>
<div class="snap"></div>
<div class="snap"></div>
<div class="snap"></div>
<div class="snap"></div>
<div class="snap"></div>
</div>
<div
id="lang1Container"
style="
background-color: bisque;
min-width: 300px;
min-height: 400px;
border-color: red;
border-style: dashed;
margin: 10px;
display: flex;
flex-direction: column;
"
>
<div class="header">lang1Container - English Words</div>
<div id="item1" class="lang1Item">Lang Item 1</div>
<div id="item2" class="lang1Item">Lang Item 2</div>
<span id="item3" class="lang1Item">Lang Item 3</span>
<span id="item4" class="lang1Item">Lang Item 4</span>
</div>
</div>
<script>
let lang1Container = document.getElementById("lang1Container");
let meaningContainer = document.getElementById("lang1MeaningContainer");
let lang1Items = document.getElementsByClassName("lang1Item");
console.log("length:" + lang1Items.length);
for (let i = 0; i < lang1Items.length; i++) {
let item = lang1Items[i];
item.addEventListener("mousedown", (e) => {
onMouseDown(e, item);
});
document.body.addEventListener("mousemove", (e) => {
onMouseMove(e, item);
});
item.addEventListener("mouseup", (e) => {
onMouseUp(e, item);
});
}
let mouseOffset = { x: 0, y: 0 };
let isMouseDown = false;
// for (let i = 0; i < 6; i++) {
// let snap = document.createElement("div");
// snap.className = "snap";
// meaningContainer.appendChild(snap);
// }
let doElsCollide = function (el1, el2) {
el1.offsetBottom = el1.offsetTop + el1.offsetHeight;
el1.offsetRight = el1.offsetLeft + el1.offsetWidth;
el2.offsetBottom = el2.offsetTop + el2.offsetHeight;
el2.offsetRight = el2.offsetLeft + el2.offsetWidth;
return !(
el1.offsetBottom < el2.offsetTop ||
el1.offsetTop > el2.offsetBottom ||
el1.offsetRight < el2.offsetLeft ||
el1.offsetLeft > el2.offsetRight
);
};
function snapMeaning(item, container) {
let box = container.getBoundingClientRect();
item.style.left = box.x + "px";
item.style.top = box.y + "px";
}
function onMouseDown(e, item) {
isMouseDown = true;
mouseOffset = {
x: item.offsetLeft - e.clientX,
y: item.offsetTop - e.clientY,
};
item.style.backgroundColor = "red";
}
function onMouseMove(e, item) {
e.preventDefault();
if (isMouseDown) {
item.style.left = e.clientX + mouseOffset.x + "px";
let tmpStyle = getComputedStyle(item);
let strMarginTop = tmpStyle.marginTop;
let tmpMarginTop = strMarginTop.replace("px", "");
item.style.top = e.clientY - tmpMarginTop + mouseOffset.y + "px"; // zero margin is used in CSS definition, otherwise margin amount need to be subtracted from the item.style.top value to have a proper event reaction. UU
// checking collusions with snaps
let snaps = document.getElementsByClassName("snap");
//console.log("Started checking");
for (let i = 0; i < snaps.length; i++) {
if (doElsCollide(item, snaps[i])) {
snaps[i].className = "snap over";
//console.log("[" + Date.now() + "]", "Collides with " + i);
} else {
snaps[i].className = "snap";
}
}
//console.log("Ended checking");
}
}
function onMouseUp(e, item) {
isMouseDown = false;
let snaps = document.getElementsByClassName("snap");
for (let i = 0; i < snaps.length; i++) {
if (doElsCollide(item, snaps[i])) {
snapMeaning(item, snaps[i]);
}
}
item.className = "lang1Item";
}
</script>
</body>
</html>
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>
i have a small html app that only changes background color of html body to randomly generated hexadecimal color. Problem i have is that when i click on the button new background color appears not only on body but it also effects background color of the button. In my css i defined that background color of the button should always be the same.
Do you know how to keep the background color of the button always same and independent of the body?
Bad background color inside of the button
Here is my code:
var button = document.getElementById('btn')
function createColorSegment(value) {
const Segment = {}
Segment.value = value
return Segment
}
button.onclick = function() {
const r1 = createColorSegment(undefined)
const r2 = createColorSegment(undefined)
const g1 = createColorSegment(undefined)
const g2 = createColorSegment(undefined)
const b1 = createColorSegment(undefined)
const b2 = createColorSegment(undefined)
function HexadecimalColor(colorSegment) {
var numberOfColorSegment = Math.floor(Math.random() * 16)
if (numberOfColorSegment == 10) {
colorSegment.value = 'a'
}
else if (numberOfColorSegment == 11) {
colorSegment.value = 'b'
}
else if (numberOfColorSegment == 12) {
colorSegment.value = 'c'
}
else if (numberOfColorSegment == 13) {
colorSegment.value = 'd'
}
else if (numberOfColorSegment == 14) {
colorSegment.value = 'e'
}
else if (numberOfColorSegment == 15) {
colorSegment.value = 'f'
}
else {
colorSegment.value = numberOfColorSegment
}
}
HexadecimalColor(r1)
HexadecimalColor(r2)
HexadecimalColor(g1)
HexadecimalColor(g2)
HexadecimalColor(b1)
HexadecimalColor(b2)
console.log(r1.value)
console.log(r2.value)
console.log(g1.value)
console.log(g2.value)
console.log(b1.value)
console.log(b2.value)
var HexColor = "#" + r1.value + r2.value + g1.value + g2.value + b1.value + b2.value
console.log(HexColor)
document.getElementsByTagName('body')[0].style.backgroundColor = HexColor
document.getElementsByClassName('hex-color-name')[0].innerText = "HEX COLOR: " + HexColor
}
* {
padding: 0;
margin: 0;
}
body {
display: flex;
justify-content: center;
}
.container {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
.hex-color-name {
font-family: 'Trebuchet MS';
font-weight: bold;
font-size: 36px;
padding-bottom: 10px;
text-transform: uppercase;
}
.button {
position: absolute;
right: 50%;
transform: translateX(+50%);
height: 40px;
width: 100px;
border-radius: 4px;
font-size: 18px;
font-weight: bold;
cursor: pointer;
background-color:rgba(0, 0, 0, 0.6);
color: white;
border: 2px solid rgba(128, 128, 128, 0.8);
}
.button:hover {
color: white;
background-color:rgba(0, 0, 0, 0.7);
}
.button:focus {
outline: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<script defer src="script.js"></script>
<title>Project2</title>
</head>
<body>
<div class="container">
<div class="hex-color-name">HEX COLOR:</div>
<button type="button" id="btn" class="button">Click me!</button>
</div>
</body>
</html>
You use opacity on your button.
background-color:rgba(0, 0, 0, 0.6); <-- .6 for the alpha
border: 2px solid rgba(128, 128, 128, 0.8); <-- .8 for the alpha
background-color:rgba(0, 0, 0, 0.7); <-- .7 for the alpha
So the color of the background effects the color of the button since it is not opaque. If you do not want that to happen do not use opacity.
.bg1 {
background-color: rgba(0, 0, 0, 0.6);
}
.bg2 {
background-color: rgb(100, 100, 100);
}
<button class="bg1">Test</button>
<button class="bg2">Test</button>
<div style="background-color: lime;">
<button class="bg1">Test</button>
<button class="bg2">Test</button>
</div>
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);
}
I am using the following css code:
html {
background: #2B2B2B url(images/bg.gif) repeat;
}
body {
max-width: 1000px;
margin: 0px auto;
font-family: sans-serif;
margin: 0 auto;
}
header,
footer,
aside {
display: block;
}
h1 {
text-align: center;
color: rgba(0, 0, 0, 0.6);
text-shadow: 2px 8px 6px rgba(0, 0, 0, 0.2), 0px -5px 35px rgba(255, 255, 255, 0.3);
text-decoration: underline;
}
label {
display: block;
}
fieldset {
border: 0px dotted red;
width: 400px;
margin: 0 auto;
}
input,
select {
width: 400px;
height: 30px;
border-radius: 5px;
padding-left: 10px;
font-size: 14px;
}
select {
line-height: 30px;
background: #f4f4f4;
}
button {
font-size: 14px;
padding: 5px;
background: #333333;
color: #FFFCEC;
float: right;
width: 100px;
}
button:hover {
font-size: 16px;
}
#edit {
background: #DC5B21;
}
#delete {} #course,
#name,
#profesor,
#subject {
background: #ABDCD6;
}
label {
font-size: 15px;
font-weight: bold;
color: #282827;
}
table {
border-spacing: 0.5rem;
border-collapse: collapse;
margin: 0 auto;
background: #ABDCD6;
}
th {
background: #E9633B;
}
th,
td {
border: 2px solid black;
padding: 10px;
}
td {
font-weight: bold;
font-style: oblique;
}
tr:nth-child(even) {
background: #ABDCD6
}
tr:nth-child(odd) {
background: #DCD8CF
}
.container {
width: 1000px;
margin: 0 auto;
}
.headerbar {
width: 988px;
float: left;
}
.headerbar.top {
background: linear-gradient(45deg, rgba(255, 102, 13, 1) 3%, rgba(255, 109, 22, 1) 32%, rgba(255, 121, 38, 1) 77%, rgba(255, 121, 38, 1) 100%);
min-height: 100px;
border-radius: 19px 30px 0px 0px;
box-shadow: #938D94 7px 7px 5px;
}
.headerbar.bottom {
background: linear-gradient(45deg, rgba(255, 102, 13, 1) 3%, rgba(255, 109, 22, 1) 32%, rgba(255, 121, 38, 1) 77%, rgba(255, 121, 38, 1) 100%);
min-height: 60px;
border-radius: 25px;
border-radius: 0px 0px 37px 34px;
box-shadow: #938D94 7px 1px 5px;
}
.leftbar {
width: 50%;
background: #EB593C;
min-height: 605px;
float: left;
border-radius: 4px;
border: 3px dashed #282827;
}
.rightbar {
width: 47%;
background: #221E1D;
min-height: 595px;
float: left;
padding: 5px;
border: 2px solid #EB593C;
box-shadow: #938D94 5px 5px 5px;
}
#submit,
#clear {
border-radius: 25px;
}
input:focus {
border: 1px solid #FF9933;
}
#media screen and (max-width: 700px) {
.leftbar,
.rightbar {
float: none;
}
.headerbar.top h1 {
margin-left: 50px;
text-align: center;
float: left;
}
and here is my HTML page very simple
<!DOCTYPE html>
<html>
<head>
<title>My web app</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="mystyle2.css" rel="stylesheet"/>
<script>
var studentsArray = [];
var selectedIndex = -1;
function init() {
document.getElementById("tablerows").innerHTML = "";
if (localStorage.studentsRecord) {
studentsArray = JSON.parse(localStorage.studentsRecord);
for (var i = 0; i < studentsArray.length; i++) {
prepareTableCell(i, studentsArray[i].course, studentsArray[i].name, studentsArray[i].profesor, studentsArray[i].subject);
}
}
}
function onRegisterPressed() {
if(validate()){
var course = document.getElementById("course").value;
var name = document.getElementById("name").value;
var profesor = document.getElementById("profesor").value;
var subject = document.getElementById("subject").value;
var stuObj = {course: course, name: name, profesor: profesor, subject: subject};
if (selectedIndex === -1) {
studentsArray.push(stuObj);
} else {
studentsArray.splice(selectedIndex, 1, stuObj);
}
localStorage.studentsRecord = JSON.stringify(studentsArray);
init();
onClarPressed();
}else{
}
}
function prepareTableCell(index, course, name, profesor, subject) {
var table = document.getElementById("tablerows");
var row = table.insertRow();
var courseCell = row.insertCell(0);
var nameCell = row.insertCell(1);
var profesorCell = row.insertCell(2);
var subjectCell = row.insertCell(3);
var actionCell = row.insertCell(4);
courseCell.innerHTML = course;
nameCell.innerHTML = name;
profesorCell.innerHTML = profesor;
subjectCell.innerHTML = subject;
actionCell.innerHTML = '<button id="edit" onclick="onEditPressed(' + index + ')">Edit</button><br/><button id="delete" onclick="deleteTableRow(' + index + ')">Delete</button>';
}
function deleteTableRow(index) {
studentsArray.splice(index, 1);
localStorage.studentsRecord = JSON.stringify(studentsArray);
init();
}
function onClarPressed() {
selectedIndex = -1;
document.getElementById("course").value = "";
document.getElementById("name").value = "";
document.getElementById("profesor").value = "";
document.getElementById("subject").value = "Math";
document.getElementById("submit").innerHTML = "Register";
}
function onEditPressed(index) {
selectedIndex = index;
var stuObj = studentsArray[index];
document.getElementById("course").value = stuObj.course;
document.getElementById("name").value = stuObj.name;
document.getElementById("profesor").value = stuObj.profesor;
document.getElementById("subject").value = stuObj.subject;
document.getElementById("submit").innerHTML = "Update";
}
function validate(){
var errors = [];
var re = /^[\w]+$/;
var id = document.getElementById("course");
if(id.value==="" ){
errors.push("Course name is empty");
}else if(id.value.length<3){
errors.push("Course name is to shoort");
}else if(!re.test(id.value)){
errors.push("Input contains invalid characters");
}
var name = document.getElementById("name");
var regEx = /^[a-zA-Z ]+$/;
if(name.value===""){
errors.push("Name cannot be empty");
}else if(!regEx.test(name.value)){
errors.push("Name contains invalid characters");
}
var profesor = document.getElementById("profesor");
if(profesor.value===""){
errors.push("Professor field cannot be empty");
}else if(!regEx.test(profesor.value)){
errors.push("Professor field contains invalid characters");
}
if(errors.length>0){
var message = "ERRORS:\n\n";
for(var i = 0;i<errors.length;i++){
message+=errors[i]+"\n";
}
alert(message);
return false;
}
return true;
}
</script>
</head>
<body onload="init()">
<header class="headerbar top"><h1>ITEC3506: Assignment#2</h1></header>
<aside class="leftbar">
<div>
<fieldset>
<label for="course"><span>Course Name</span></label>
<input type="text" placeholder="enter name of course" id="course">
</fieldset>
<fieldset>
<label for="name">Your Name</label>
<input type="text" placeholder="enter your name" id="name">
</fieldset>
<fieldset>
<label for="profesor">Course Professor</label>
<input type="text" placeholder="enter course Professor" id="profesor">
</fieldset>
<fieldset>
<label for="subject">Subject</label>
<select id="subject">
<option value="Math">Math</option>
<option value="Physics">Physics</option>
<option value="Chemistry">Chemistry</option>
<option value="English">English</option>
<option value="CS">CS</option>
</select>
</fieldset>
<fieldset>
<label for="submit"> </label>
<button id="submit" onclick="onRegisterPressed()">Submit</button>
<button id="clear" onclick="onClarPressed()">Clear</button>
</fieldset>
</div>
</aside>
<aside class="rightbar">
<table id="regtable">
<thead>
<tr>
<th>Course</th>
<th>Student</th>
<th>Professor</th>
<th>Subject</th>
<th>Action</th>
</tr>
</thead>
<tbody id="tablerows">
</tbody>
</table>
</aside>
<footer class="headerbar bottom"></footer>
</div>
</body>
</html>
My question is how can I transform this code into a responsive site.
Everything is resizing normally, except I cannot seem to resize my table and form. Could somebody help me?
A few things going on here.
First, you don't have a set width on a few of your fields, so change:
fieldset{
border: 0px dotted red;
width: 400px;
margin: 0 auto;
}
to:
fieldset{
border: 0px dotted red;
width: 400px;
margin: 0 auto;
max-width: 100%;
}
Also change .headerbar from width: 988px; to width: 100%;.
For responsive frameworks, you need to ensure that you never have a set a fixed width without ensuring there is a max-width attached to it, otherwise your content size will never drop below the size of your fixed width.
Second, I noticed the following:
.leftbar{
width: 50%;
background: #EB593C;
min-height: 605px;
float: left;
border-radius: 4px;
border: 3px dashed #282827;
}
You didn't specifically call this out, but when I check your code in a smaller view, I notice that your width: 50%; is causing the backgrounds to look off, which does not seem to be your intention. I would recommend adding .leftbar { width: 100%; } as well as .rightbar { width: 100%; } inside of #media screen and (max-width:700px){
That just leaves the table. Tables do not automatically break down, so are generally not something we want to use when developing a responsive site, but of course sometimes there is no getting around this.
There are a few ways to tackle the issue with the table. One is to set the table to display:block; and apply overflow-x: scroll; to it inside of your #media screen and (max-width:700px){, which will allow the user to scroll left/right when viewing it from smaller screens. Another is to use one of the various Javascript plugins that can achieve this.
Hope this helps get you on the right track. Best of luck!
Do not set width for these
input,select{/*width: 400px;*/}
fieldset{/*width: 400px;*/}
If you are setting width obviously you cannot obtain a responsive layout