localStorage cant save information - javascript

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);
}

Related

When i click the next or previous the thumbnail's are not changed

its an image slider when I click the next I needs to change the image in the thumbnails also but its not working. also not showing main picture when I click in the the first picture and the second is working but third also not working...
thumbnail's are not change through next and previous...
in slider images are change through next and previous but the thumbnails are not change with image...
Code.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<style>
.newsslider {
width: 100%;
height: 800px;
background-color:#766582;
}
.text {
text-align: center;
font-size: 40px;
color: white;
margin-bottom: -101px;
}
.btn1,
.btn2 {
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
margin-top: -30px;
padding: 16px;
color: #52492f;
font-weight: bold;
font-size: 20px;
border-radius: 0 3px 3px 0;
user-select: none;
}
.btn2 {
position: absolute;
right: 0;
border-radius: 3px 0 0 3px;
}
.btn1:hover,
.btn2:hover {
background-color: rgba(0, 0, 0, 0.8);
color: white;
}
.onebtn {}
.twobtn {}
.thumbs {
display: flex;
padding-top: 6%;
align-items: center;
justify-content: center;
list-style: none;
}
.thumbs li {
width: 12%;
padding: 10px;
margin: 1%;
}
.thumbs li img {
width: 100%;
}
.img12:hover {
box-shadow: 0 0 2px 1px rgba(0, 140, 186, 0.5);
}
</style>
</head>
<body>
<div class="newsslider">
<p class="text" id="demo"><img id="demo1" src="img5.png" width=30%; height=400px;> </p>
<div class="onebtn">
<button id="btn1" class="btn1" type="button" class="prev" onclick="prev()">PREV</button>
</div>
<div class="twobtn">
<button id="btn2" class="btn2" type="button" class="next" onclick="next()">NEXT</button>
</div>
<p id="newsArr1" class="text" style="font-size:40px; font-weight:bolder; color: #521d2c;">Hi,</p>
<ul class="thumbs">
<li class="img12" onclick="thumbchange(1)"><img src="img5.png" width=500%;></li>
<li class="img12" onclick="thumbchange(2)"><img src="img2.png"></li>
<li class="img12" onclick="thumbchange(3)"><img src="img4.png"></li>
</ul>
</div>
<script>
var newsArr = ['<img src="img5.png"width = 30%; height=400px;>',
'<img src="img2.png"width = 30%; height=400px; >',
'<img src="img4.png" width = 30%; height=400px;>'];
var newsArr1 = ["Hi",
"This is Urraan",
"Urraan is a digital gateway"];
var i = 0;
var x = document.getElementById("demo");
var y = document.getElementById("newsArr1");
// var timeoutId;
function next() {
// if (timeoutId) {
// clearTimeout(timeoutId);
// }
i++;
if (i < newsArr.length) {
x.innerHTML = newsArr[i];
y.innerHTML = newsArr1[i];
} else {
i = 0;
x.innerHTML = newsArr[i];
y.innerHTML = newsArr1[i];
}
// timeoutId = setTimeout(next, 2000);
}
function prev() {
i--;
if (i >= 0) {
x.innerHTML = newsArr[i];
y.innerHTML = newsArr1[i];
} else {
i = newsArr.length - 1;
x.innerHTML = newsArr[i];
y.innerHTML = newsArr1[i];
}
}
function thumbchange(num) {
var thumb = 'img' + num + '.png';
document.getElementById("demo1").src = thumb;
}
</script>
</body>
</html>
you problem solved ... please try it.
var newsArr = ['<img src="https://www.w3schools.com/bootstrap4/la.jpg"width = 100%; height=400px;>',
'<img src="https://www.w3schools.com/bootstrap4/chicago.jpg"width = 100%; height=400px; >',
'<img src="https://www.w3schools.com/bootstrap4/ny.jpg" width = 100%; height=400px;>'];
var newsArr1 = ["Hi",
"This is Urraan",
"Urraan is a digital gateway"];
var i = 0;
var x = document.getElementById("demo");
var y = document.getElementById("newsArr1");
// var timeoutId;
function next() {
// if (timeoutId) {
// clearTimeout(timeoutId);
// }
i++;
if (i < newsArr.length) {
x.innerHTML = newsArr[i];
y.innerHTML = newsArr1[i];
} else {
i = 0;
x.innerHTML = newsArr[i];
y.innerHTML = newsArr1[i];
}
// timeoutId = setTimeout(next, 2000);
setThumbnailFocus(i)
}
function prev() {
i--;
if (i >= 0) {
x.innerHTML = newsArr[i];
y.innerHTML = newsArr1[i];
} else {
i = newsArr.length - 1;
x.innerHTML = newsArr[i];
y.innerHTML = newsArr1[i];
}
setThumbnailFocus(i)
}
function thumbchange(num) {
x.innerHTML = newsArr[num-1];
y.innerHTML = newsArr1[num-1];
setThumbnailFocus(num-1)
}
function setThumbnailFocus(num){
var elems = document.querySelectorAll(".thumbs .selected");
[].forEach.call(elems, function(el) {
el.classList.remove("selected");
});
document.getElementsByClassName("img12")[num].classList.add("selected");
}
.newsslider {
width: 100%;
height: 800px;
background-color:#766582;
}
.text {
text-align: center;
font-size: 40px;
color: white;
margin-bottom: -101px;
}
.btn1,
.btn2 {
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
margin-top: -30px;
padding: 16px;
color: #52492f;
font-weight: bold;
font-size: 20px;
border-radius: 0 3px 3px 0;
user-select: none;
}
.btn2 {
position: absolute;
right: 0;
border-radius: 3px 0 0 3px;
}
.btn1:hover,
.btn2:hover {
background-color: rgba(0, 0, 0, 0.8);
color: white;
}
.onebtn {}
.twobtn {}
.thumbs {
display: flex;
padding-top: 6%;
align-items: center;
justify-content: center;
list-style: none;
}
.thumbs li {
width: 12%;
padding: 10px;
margin: 1%;
}
.thumbs li img {
width: 100%;
}
.img12:hover {
box-shadow: 0 0 2px 1px rgba(0, 140, 186, 0.5);
}
.selected{
border:solid 2px red
}
<div class="newsslider">
<p class="text" id="demo"><img id="demo1" src="https://www.w3schools.com/bootstrap4/la.jpg" width=100%; height=400px;> </p>
<div class="onebtn">
<button id="btn1" class="btn1" type="button" class="prev" onclick="prev()">PREV</button>
</div>
<div class="twobtn">
<button id="btn2" class="btn2" type="button" class="next" onclick="next()">NEXT</button>
</div>
<p id="newsArr1" class="text" style="font-size:40px; font-weight:bolder; color: #521d2c;">Hi,</p>
<ul class="thumbs">
<li class="img12 selected" onclick="thumbchange(1)"><img src="https://www.w3schools.com/bootstrap4/la.jpg" width=500%;></li>
<li class="img12" onclick="thumbchange(2)"><img src="https://www.w3schools.com/bootstrap4/chicago.jpg"></li>
<li class="img12" onclick="thumbchange(3)"><img src="https://www.w3schools.com/bootstrap4/ny.jpg"></li>
</ul>
</div>
The first issue I found is that you have this code:
<p class="text" id="demo"><img id="demo1" src="img5.png" width=30%; height=400px;> </p>
And here you didn't use part with setting id:
var newsArr = ['<img //here is no id// src="img5.png"width = 30%; height=400px;>',
'<img //here is no id// src="img2.png"width = 30%; height=400px; >',
'<img //here is no id// src="img4.png" width = 30%; height=400px;>'];
And when you are clicking on next and prev button, you are removing your id unconsciously, so your thumbchange() function stop working, because it is based on id.

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.

Range Slider how Implement Touch Mobile?

How could one implement mobile touch on this code to make the range slider work on mobile?
I found a lot of tutorials on the internet but they all contained jquery ui but I have a range slider without ui and I'm not good at JS.
$("document").ready(function() {
const rangeSliderAmount = document.querySelector('.lc-range-slider-amount');
const rangeSliderMonth = document.querySelector('.lc-range-slider-month');
const rangeValueBarAmount = document.querySelector('#lc-range-value-bar-amount');
const rangeValueBarMonth = document.querySelector('#lc-range-value-bar-month');
const rangeValueAmount = document.querySelector('#lc-range-value-amount');
const rangeValueMonth = document.querySelector('#lc-range-value-month');
const rangeAmount = document.getElementById("lc-amount");
const rangeMonth = document.getElementById("lc-month");
let isDown = false;
function dragHandler() {
isDown = !isDown;
if (!isDown) {
rangeValueAmount.style.setProperty('opacity', '1');
rangeValueMonth.style.setProperty('opacity', '1');
} else {
rangeValueAmount.style.setProperty('opacity', '1');
rangeValueMonth.style.setProperty('opacity', '1');
}
}
function dragOn(e) {
if (!isDown) return;
rangeValueHandler();
}
function rangeValueHandler() {
amountPercentage = `${((rangeSliderAmount.value - 500) * 100) / (6000 - 500)}%`;
monthPercentage = `${((rangeSliderMonth.value - 6) * 100) / (60 - 6)}%`;
rangeValueBarAmount.style.setProperty('width', amountPercentage);
rangeValueBarMonth.style.setProperty('width', monthPercentage);
rangeValueAmount.innerHTML = `${rangeSliderAmount.value}`;
rangeValueMonth.innerHTML = `${rangeSliderMonth.value}`;
rangeAmount.innerHTML = `${rangeSliderAmount.value}`;
rangeMonth.innerHTML = `${rangeSliderMonth.value}`;
vypocetSplatka();
}
rangeValueHandler();
rangeSliderAmount.addEventListener('mousedown', dragHandler);
rangeSliderAmount.addEventListener('mousemove', dragOn);
rangeSliderAmount.addEventListener('mouseup', dragHandler);
rangeSliderAmount.addEventListener('click', rangeValueHandler);
rangeSliderMonth.addEventListener('mousedown', dragHandler);
rangeSliderMonth.addEventListener('mousemove', dragOn);
rangeSliderMonth.addEventListener('mouseup', dragHandler);
rangeSliderMonth.addEventListener('click', rangeValueHandler);
function slideValue(inputElement) {
var sliderElement = inputElement.closest('.lc-slider').find('.slider');
var val = parseInt(inputElement.val().replace(' ', '')) || 0;
var sliderMax = $(sliderElement).slider('option', 'max');
var sliderMin = $(sliderElement).slider('option', 'min');
if (val > sliderMax) {
val = sliderMax;
}
if (val < sliderMin) {
val = sliderMin;
}
$(sliderElement).slider('value', val);
val = formatNumber(val, 0, ',', ' ');
if (inputElement.val() !== val) {
inputElement.val(val);
}
}
$('.slider-value .value').change(function(){
slideValue($(this));
vypocetSplatka();
});
vypocetSplatka();
$('.insurance-box').on('change', 'input[name=poistenie]', function(){
vypocetSplatka();
});
function formatNumber(number, decimals, dec_point, thousands_sep) {
var str = number.toFixed(decimals ? decimals : 0).toString().split('.');
var parts = [];
for (var i = str[0].length; i > 0; i -= 3) {
parts.unshift(str[0].substring(Math.max(0, i - 3), i));
}
str[0] = parts.join(thousands_sep ? thousands_sep : ',');
return str.join(dec_point ? dec_point : '.');
}
function vypocetSplatka() {
var mesiace = parseInt($('[data-value="months"]').html());
var pozicka = parseInt($('[data-value="loan"]').html().replace(' ', ''));
var poplatok = (pozicka / 100) * 2;
$('.hascharge').show();
if(pozicka <= -1){
poplatok = 0;
$('.hascharge').hide();
}
var benefit = 2;
var perc, payment_mpr, payment_mpr_full, insurance, payment_month, payment_month_full, suma, suma_full, rateValue, rpmn;
$('[data-value="charge"]').text(poplatok);
$('[data-value="months-val"]').text(mesiace);
$('span[data-value="loan"]').text(price_format(pozicka));
if (pozicka <= 300) {
perc = 15.18;
} else if (pozicka <= 700) {
perc = 13.9;
} else if (pozicka <= 1499) {
perc = 11.4;
} else {
perc = 8.9;
}
if (pozicka <= 300 && mesiace<=60 && mesiace>=6) {
perc = 15.18;
} else if (pozicka <= 679 && mesiace<=60 && mesiace>=6) {
perc = 13.9;
} else if (pozicka <= 720 && mesiace<=60 && mesiace>=6) {
perc = 10.01;
} else if (pozicka <= 1499 && mesiace<=60 && mesiace>=6) {
perc = 11.4;
} else if (mesiace<=60 && mesiace>=6) {
perc = 8.9;
}
var diff = (Math.round((perc - benefit) * 100) / 100).toFixed(2);
diff = diff.replace('.', ',');
$('[data-value="interest"]').text(diff);
var pmt_ir_full = perc / 1200;
var pmt_ir = (perc - benefit) / 1200;
//pmt_ir = 13.9 / 1200;
var pmt_np = mesiace;
var pmt_pv = -pozicka;
if (pmt_np > 0 && pmt_pv < 0) {
payment_mpr = pmt(pmt_ir, pmt_np, pmt_pv);
payment_mpr_full = pmt(pmt_ir_full, pmt_np, pmt_pv);
$('.insurance-label').text('');
// poistenie
insurance = 0;
if ($('input[name=poistenie]:checked').val() === '1') {
insurance += 0.081 * pozicka / 100;
$('.insurance-label').text('vrátane poistenia');
}
if ($('input[name=poistenie]:checked').val() === '2') {
insurance += 0.148 * pozicka / 100;
$('.insurance-label').text('vrátane poistenia');
}
//payment_mpr += ' €';
payment_month = rd(payment_mpr + insurance);
payment_month_full = rd(payment_mpr_full + insurance);
payment_mpr = rd(payment_mpr);
suma = payment_month * mesiace + poplatok;
suma_full = payment_month_full * mesiace + poplatok;
$('#clientsave').html(price_format(suma_full - suma) + ' €');
} else {
payment_mpr = '';
}
$('[data-value="fee"]').html(price_format(payment_month));
$('[data-value="fee-val"]').text(price_format(payment_mpr));
rateValue = rate(pmt_np, payment_mpr, -pozicka + poplatok);
rpmn = (Math.pow(rateValue + 1, 12) - 1) * 100;
$('[data-value="rpmn-val"]').text(price_format(rpmn));
$('[data-value="sum"]').text(price_format(payment_mpr * mesiace + poplatok));
$('#vyskaF').val(pozicka);
$('#splatnostF').val(mesiace);
if ($('input[name=poistenie]:checked').val() === '0') { $('#poistenieF').val("bez poistenia"); };
if ($('input[name=poistenie]:checked').val() === '1') { $('#poistenieF').val("základné"); };
if ($('input[name=poistenie]:checked').val() === '2') { $('#poistenieF').val("rozšírené"); };
//bez benefitu repre priklad *NEW 16.11:2017 -- START
var diffWo = (Math.round((perc) * 100) / 100).toFixed(2);
diffWo = diffWo.replace('.', ',');
payment_mpr_full = rd(payment_mpr_full);
var rateValue_full, rpmn_full;
rateValue_full = rate(pmt_np, payment_mpr_full, -pozicka + poplatok);
rpmn_full = (Math.pow(rateValue_full + 1, 12) - 1) * 100;
$('[data-value="interest-wo"]').text(diffWo);
$('[data-value="fee-val-wo"]').text(price_format(payment_mpr_full));
$('[data-value="rpmn-val-wo"]').text(price_format(rpmn_full));
$('[data-value="sum-wo"]').text(price_format(payment_mpr_full * mesiace + poplatok));
// *NEW 16.11:2017 -- END
}
function rd(n) {
var r = Math.round(n * 100) / 100;
return r;
}
function price_format(number, decimals, decPoint, thousandsSep) {
decimals = decimals || 2;
number = parseFloat(number);
if (!decPoint || !thousandsSep) {
decPoint = ',';
thousandsSep = ' ';
}
var roundedNumber = Math.round(Math.abs(number) * ('1e' + decimals)) + '';
var numbersString = decimals ? roundedNumber.slice(0, decimals * -1) : roundedNumber;
var decimalsString = decimals ? roundedNumber.slice(decimals * -1) : '';
var formattedNumber = '';
while (numbersString.length > 3) {
formattedNumber += thousandsSep + numbersString.slice(-3);
numbersString = numbersString.slice(0, -3);
}
return (number < 0 ? '-' : '') + numbersString + formattedNumber + (decimalsString ? (decPoint + decimalsString) : '');
}
//function pmt(ir, np, pv, fv = 0, type = 0) { //defaul value nie je vsade podporovane!!! RBR
function pmt(ir, np, pv, fv, type) {
var fv = (typeof fv !== 'undefined') ? fv : 0;
var type = (typeof type !== 'undefined') ? type : 0;
/*
* ir - interest rate per month
* np - number of periods (months)
* pv - present value
* fv - future value
* type - when the payments are due:
* 0: end of the period, e.g. end of month (default)
* 1: beginning of period
*/
if (ir === 0) {
return -(pv + fv) / np;
}
var pvif = Math.pow(1 + ir, np);
var pmt = -ir * pv * (pvif + fv) / (pvif - 1);
if (type === 1) {
pmt /= (1 + ir);
}
return pmt;
}
function rate(paymentsPerYear, paymentAmount, presentValue, futureValue, dueEndOrBeginning, interest) {
//If interest, futureValue, dueEndorBeginning was not set, set now
if (interest == null) {
interest = 0.01;
}
if (futureValue == null) {
futureValue = 0;
}
if (dueEndOrBeginning == null) {
dueEndOrBeginning = 0;
}
var FINANCIAL_MAX_ITERATIONS = 128; //Bet accuracy with 128
var FINANCIAL_PRECISION = 0.0000001; //1.0e-8
var y, y0, y1, x0, x1 = 0,
f = 0,
i = 0;
var rate = interest;
if (Math.abs(rate) < FINANCIAL_PRECISION) {
y = presentValue * (1 + paymentsPerYear * rate) + paymentAmount * (1 + rate * dueEndOrBeginning) * paymentsPerYear + futureValue;
} else {
f = Math.exp(paymentsPerYear * Math.log(1 + rate));
y = presentValue * f + paymentAmount * (1 / rate + dueEndOrBeginning) * (f - 1) + futureValue;
}
y0 = presentValue + paymentAmount * paymentsPerYear + futureValue;
y1 = presentValue * f + paymentAmount * (1 / rate + dueEndOrBeginning) * (f - 1) + futureValue;
// find root by Newton secant method
i = x0 = 0.0;
x1 = rate;
while ((Math.abs(y0 - y1) > FINANCIAL_PRECISION) &&
(i < FINANCIAL_MAX_ITERATIONS)) {
rate = (y1 * x0 - y0 * x1) / (y1 - y0);
x0 = x1;
x1 = rate;
if (Math.abs(rate) < FINANCIAL_PRECISION) {
y = presentValue * (1 + paymentsPerYear * rate) + paymentAmount * (1 + rate * dueEndOrBeginning) * paymentsPerYear + futureValue;
} else {
f = Math.exp(paymentsPerYear * Math.log(1 + rate));
y = presentValue * f + paymentAmount * (1 / rate + dueEndOrBeginning) * (f - 1) + futureValue;
}
y0 = y1;
y1 = y;
++i;
}
return rate;
}
});
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
background: #EFEEEE;
}
.lc-container {
margin-top: 100px;
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
}
.lc-sliders {
width: 70%;
padding: 0;
background-color: #fff;
border-top: 5px solid #E9EFF4;
border-bottom: 5px solid #E9EFF4;
border-left: 5px solid #E9EFF4;
border-top-left-radius: 10px;
border-bottom-left-radius: 10px;
}
.lc-slider {
width: 100%;
margin: 0;
padding: 10px;
background: transparent;
}
.lc-slider:first-child {
border-bottom: 1px solid #E9EFF4;
}
.lc-txtinp {
display: flex;
justify-content: space-between;
align-items: center;
}
.lc-amount {
width: 90px;
height: 90px;
position: relative;
display: block;
padding-top: 13px;
line-height: 30px;
text-align: center;
font-size: 26px;
font-weight: bold;
color: #FC6E50;
font-style: normal;
line-height: normal;
border-radius: 50%;
box-sizing: border-box;
border: 5px solid #EFEEEE;
transform-origin: center center;
background: #fff;
}
.lc-amount::after {
display: block;
content: "EUR";
font-size: 16px;
letter-spacing: 0.07em;
margin-top: -2px;
}
.lc-month {
width: 90px;
height: 90px;
position: relative;
display: block;
padding-top: 13px;
line-height: 30px;
text-align: center;
font-size: 26px;
font-weight: bold;
color: #FC6E50;
font-style: normal;
line-height: normal;
border-radius: 50%;
box-sizing: border-box;
border: 5px solid #EFEEEE;
transform-origin: center center;
background: #fff;
}
.lc-month::after {
display: block;
content: "Mes.";
font-size: 16px;
letter-spacing: 0.07em;
margin-top: -2px;
}
.lc-ranger {
width: 100%;
}
.lc-range {
margin: 20px 0;
position: relative;
}
.lc-minmax {
margin-top: 30px;
width: 100%;
display: flex;
justify-content: space-between;
align-items: center;
}
.lc-txtinp span.span,
.lc-minmax span.span {
font-size: 14px;
font-weight: 400;
}
.lc-summarize {
display: flex;
flex-direction: column;
justify-content: space-between;
width: 30%;
height: 421px;
padding: 0;
background: #fff;
border-left: 2px solid #E9EFF4;
border-top: 5px solid #E9EFF4;
border-bottom: 5px solid #E9EFF4;
border-right: 5px solid #E9EFF4;
border-top-right-radius: 10px;
border-bottom-right-radius: 10px;
}
.lc-summarize-head {
padding: 25px 0;
text-align: center;
}
.lc-summarize-head h2 {
font-size: 20px;
background: none;
color: #4d4d4d;
margin-bottom: 0;
background-repeat: no-repeat;
}
.lc-show-payment {
padding: 5px;
}
.lc-payment-show {
width: 200px;
height: 200px;
position: relative;
display: block;
margin: 0 auto;
padding-top: 60px;
line-height: 30px;
text-align: center;
font-size: 40px;
font-weight: bold;
color: #FC6E50;
font-style: normal;
line-height: normal;
border-radius: 50%;
box-sizing: border-box;
border: 5px solid #EFEEEE;
transform-origin: center center;
background: #fff;
}
.lc-payment-show::after {
display: block;
content: "EUR/MES.";
font-size: 16px;
letter-spacing: 0.07em;
margin-top: -2px;
}
.lc-accept-loan {
padding: 0;
text-align: center;
border-top: 2px solid #E9EFF4;
}
a.send-loan-details,
button.send-loan-details {
text-decoration: none;
outline: none;
border: none;
display: block;
text-align: center;
width: 100%;
padding: 15px 0;
background: #fff;
font-size: 20px;
color: #4d4d4d;
margin-bottom: 0;
background-repeat: no-repeat;
border-bottom-right-radius: 10px;
cursor: pointer;
}
a.send-loan-details:hover,
a.send-loan-details:focus,
button.send-loan-details:hover,
button.send-loan-details:focus {
background: #FC6E50;
color: #fff;
}
.lc-representative-example {
font-size: 12px;
width: 100%;
position: relative;
margin: 15px 0;
padding: 5px 0;
display: block;
}
.lc-representative-example span.spanbold {
color: #4d4d4d;
font-weight: bold;
}
.lc-range-slider-container {
position: relative;
}
input[type=range] {
-webkit-appearance: none;
margin: 10px 0;
width: 100%;
position: absolute;
top: 0;
margin: 0;
}
#lc-range-value-bar-amount {
width: 100%;
content: "0";
background-color: #FC6E50;
position: absolute;
z-index: 10000;
height: 25px;
top: 0;
margin: 0;
border-radius: 5px;
}
#lc-range-value-bar-month {
width: 100%;
content: "0";
background-color: #FC6E50;
position: absolute;
z-index: 10000;
height: 25px;
top: 0;
margin: 0;
border-radius: 5px;
}
/*
#range-value {
content:"0";
background: rgba(233, 239, 244, 0.1);;
position: absolute;
z-index: 10000;
height: 25px;
top: -65px;
margin: 0;
border-radius: 5px;
left: 50%;
transform0: translateX(-50%);
font-size: 20px;
padding: 12px;
color: #41576B;
box-shadow: 0 2px 10px 0 rgba(0,0,0,0.08);
text-align: center;
opacity: 0;
}*/
input[type=range]:focus {
outline: none;
}
input[type=range]::-webkit-slider-runnable-track {
width: 100%;
height: 25px;
cursor: pointer;
animate: 0.2s;
box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
background: #E9EFF4;
border-radius: 5px;
border: 0px solid #000101;
}
input[type=range]::-webkit-slider-thumb {
box-shadow: 0 2px 10px 0 rgba(0,0,0,0.08);
border: 14px solid #FFF;
height: 53px;
width: 53px;
border-radius: 30px;
background: #FC6E50;
cursor: pointer;
-webkit-appearance: none;
margin-top: -13.5px;
position: relative;
z-index: 1000000000;
}
input[type=range]::-moz-range-track {
width: 100%;
height: 12.8px;
cursor: pointer;
animate: 0.2s;
box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
background: #000;
border-radius: 25px;
border: 0px solid #000101;
}
input[type=range]::-moz-range-thumb {
box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
border: 0px solid #000000;
height: 20px;
width: 39px;
border-radius: 7px;
background: #000000;
cursor: pointer;
}
input[type=range]::-ms-track {
width: 100%;
height: 12.8px;
cursor: pointer;
animate: 0.2s;
background: transparent;
border-color: transparent;
border-width: 39px 0;
color: transparent;
}
input[type=range]::-ms-fill-lower {
background: #000;
border: 0px solid #000101;
border-radius: 50px;
box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
}
input[type=range]::-ms-fill-upper {
background: #000;
border: 0px solid #000101;
border-radius: 50px;
box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
}
input[type=range]::-ms-thumb {
box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
border: 0px solid #000000;
height: 20px;
width: 39px;
border-radius: 7px;
background: #000;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-12">
<div class="lc-container">
<div class="lc-sliders">
<div class="lc-slider">
<div class="lc-txtinp">
<span class="span">Zvoľte si výšku pôžičky</span>
<span id="lc-amount" class="lc-amount">2000</span>
</div>
<div class="lc-range">
<div class="lc-range-slider-container slider-value">
<input id="lc-range-amount" type="range" class="slider lc-range-slider-amount" min="500" max="6000" step="100" value="500">
<span id="lc-range-value-bar-amount"></span>
<span id="lc-range-value-amount" data-value="loan" class="value">0</span>
</div>
</div>
<div class="lc-minmax">
<span class="span">500€</span>
<span class="span">6000€</span>
</div>
</div>
<div class="lc-slider">
<div class="lc-txtinp">
<span class="span">Zvoľte si dobu splatnosti</span>
<span id="lc-month" class="lc-month">6</span>
</div>
<div class="lc-range">
<div class="lc-range-slider-container slider-value">
<input id="lc-range-month" type="range" class="slider lc-range-slider-month" min="6" max="60" step="1" value="6">
<span id="lc-range-value-bar-month"></span>
<span id="lc-range-value-month" data-value="months" class="value ">0</span>
</div>
</div>
<div class="lc-minmax">
<span class="span">6 mesiacov</span>
<span class="span">60 mesiacov</span>
</div>
</div>
</div>
<div class="lc-summarize">
<div class="lc-summarize-head">
<h2>Vaša mesačná splátka</h2>
</div>
<div class="lc-show-payment">
<span id="lc-payment-show" class="lc-payment-show value payment" data-value="fee">
0,00
</span>
</div>
<div class="lc-accept-loan">
<button type="submit" class="send-loan-details">
Chcem pôžičku
</button>
</div>
</div>
</div>
<div class="lc-representative-example">
<span class="spanbold">Reprezentatívny príklad:</span> Mesačná anuitná splátka Pôžičky s odmenou vo výške <span data-value="loan">2 000,00</span> € s úrokovou sadzbou
<span data-value="interest">13,18</span> % p.a. a splatnosťou <span data-value="months-val">60</span> mesiacov predstavuje
<span data-value="fee-val">45,69</span> €. Ročná percentuálna miera nákladov dosahuje
<span data-value="rpmn-val">15,03</span> %, počet splátok <span data-value="months-val">60</span>.
Výška poplatku za poskytnutie pôžičky je <span class="hascharge">2 % z výšky úveru, v tomto prípade</span> <span data-value="charge">40</span> €.
Celková čiastka, ktorú musí klient zaplatiť, predstavuje <span data-value="sum">2 781,40</span> eur. Na schválenie a poskytnutie pôžičky nie je právny nárok. Výška splátky je uvedená bez Poistenia schopnosti splácať úver.
</div>
</div>
</div>
</div>
You need to attach handlers for touch events to make the range sliders work in mobile. If you add the below lines to your code, it will start working in mobile.
rangeSliderAmount.addEventListener('touchstart', dragHandler);
rangeSliderAmount.addEventListener('touchmove', dragOn);
rangeSliderAmount.addEventListener('touchend', dragHandler);
rangeSliderAmount.addEventListener('touchstart', rangeValueHandler);
rangeSliderMonth.addEventListener('touchstart', dragHandler);
rangeSliderMonth.addEventListener('touchmove', dragOn);
rangeSliderMonth.addEventListener('touchend', dragHandler);
rangeSliderMonth.addEventListener('touchstart', rangeValueHandler);
Refer this document to learn about touch events in javascript:
https://developer.mozilla.org/en-US/docs/Web/API/Touch_events
Working sample based on your code:
https://plnkr.co/edit/TDLHWvaYFr1V8GQqZ9Zb

How to simplify my JS functions in a nutrition calculator?

https://codepen.io/TBD007/pen/zYxgWbv
Trying to avoid having to write a function for each button's onclick event. Currently i am using a separate function for each onclick. I am pretty sure there is a way to put all that into one single function but i just can't figure it out on my own.. Any idea to simplify the js code in order to calculate the values? Help is very much appreciated!
function test() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test2() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test2").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test3() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test3").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
Here's a the full snippet:
var result = document.getElementById("txtResult").innerHTML;
function test() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test2() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test2").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test3() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test3").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test4() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test4").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test5() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test5").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test6() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test6").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test7() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test7").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test8() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test8").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test9() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test9").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test10() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test10").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test11() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test11").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test12() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test12").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test13() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test13").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test14() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test14").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function add() {
var y = document.getElementById("txtResultItem").innerHTML;
var z = document.getElementById("txtResult").innerHTML;
document.getElementById("txtResult").innerHTML = Number(y) + Number(z);
}
function sub() {
var y = document.getElementById("txtResultItem").innerHTML;
var z = document.getElementById("txtResult").innerHTML;
document.getElementById("txtResult").innerHTML = Number(z) - Number(y);
}
function clearentry() {
document.getElementById("txtResultItem").innerHTML = 0;
document.getElementById("txtResult").innerHTML = 0;
}
.main {
width: 100%;
height: 100vh;
background: linear-gradient(to right, rgba(26, 26, 43, 0.496), rgba(26, 26, 43, 0.86)), url("https://www.miss.at/wp-content/uploads/2019/11/Technik-Panne-McDonalds-muss-400.000-Euro-an-Gewinner-zahlen-1024x683.jpg");
background-position: center;
background-size: cover;
background-repeat: no-repeat;
display: flex;
justify-content: center;
align-items: center;
}
button {
height: 60px;
width: 60px;
border: 2px solid silver;
box-shadow: 2px 2px 5px black;
position: relative;
}
#txtResult {
width: 257px;
height: 40px;
text-align: right;
background: rgba(40, 40, 53, 0.69);
margin-bottom: 5px;
box-shadow: inset -2px -2px 1px gray;
}
#txtResultItem {
width: 257px;
height: 40px;
text-align: right;
background: rgba(40, 40, 53, 0.69);
margin-bottom: 5px;
box-shadow: inset -2px -2px 1px gray;
}
button {
height: 60px;
width: 60px;
background-size: contain;
}
#btnClearEntry {
font-family: 'Raleway';
max-height: 60px;
max-width: 60px;
}
#btn1 {
background-image: url("https://img.scoop.it/aImnklIQUA5uWH212vRoWjl72eJkfbmt4t8yenImKBVvK0kTmF0xjctABnaLJIm9");
}
#btn2 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-big-mac.png?$Nutritional_Desktop$");
}
#btn3 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-hamburger.png?$Nutritional_Desktop$");
}
#btn4 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-6-chicken-mcnuggets.png?$Nutritional_Desktop$");
}
#btn5 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-crispy-caesar-chicken-mcwrap.png?$Nutritional_Desktop$");
}
#btn6 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-fries-medium.png?$Nutritional_Desktop$");
}
#btn7 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-blueberry-muffin-hero.png?$Nutritional_Desktop$");
}
#btn8 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-coca-cola.png?$Nutritional_Desktop$");
}
#btn9 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-side-caesar-salad.png?$Nutritional_Desktop$");
}
#btn10 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-egg-mcmuffin.png?$Nutritional_Desktop$");
}
#btn11 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-filet-o-fish.png?$Nutritional_Desktop$");
}
#btn12 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-quarter-pounder-cheese.png?$Nutritional_Desktop$");
}
#btn13 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-baked-apple-pie.png?$Nutritional_Desktop$");
}
#btn14 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-hot-fudge-sundae.png?$Nutritional_Desktop$")
}
#logo {
background-image: url("http://www.mcdonalds.at/sites/default/files/cms/social_media/sharelogo.png");
height: 60px;
width: 60px;
border: 0px solid rgba(40, 40, 53, 0.89);
box-shadow: 2px 2px 9px black;
}
#btnClearEntry {
background: rgba(40, 40, 53, 0.79);
border: 1px solid white;
color: white;
width: 62px;
height: 62px;
box-shadow: 2px 2px 7px black;
}
#btnplus {
color: white;
background: red;
border: 1px solid silver;
font-size: 18px;
width: 60px;
height: 60px;
box-shadow: 2px 2px 7px black;
}
#btnminus {
color: white;
background: rgba(255, 223, 15, 1);
border: 1px solid silver;
font-size: 30px;
width: 60px;
height: 60px;
box-shadow: 2px 2px 7px black;
}
#logo {
border: 1px solid white;
}
.calculator {
box-shadow: 2px 2px 10 px rgba(0, 0, 0, 0.648);
padding: 5px;
}
button:hover {
position: relative;
}
button[aria-label]:hover:after {
content: attr(aria-label);
padding: 4px 8px;
position: absolute;
left: 0;
top: 100%;
white-space: nowrap;
z-index: 20;
background: red;
color: yellow;
font-family: 'Raleway';
}
<head>
<link href="https://fonts.googleapis.com/css?family=Raleway&display=swap" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div class="main">
<div class="calculator">
<table>
<tr>
<td colspan="4">
<div style="color:white; font-family:sans-serif;font-size:20px;" id="txtResult" readonly="readonly"></div>
</td>
</tr>
<tr>
<td colspan="4">
<div style="color:white; font-family:sans-serif;font-size:16px;" id="txtResultItem"></div>
</td>
</tr>
<tr>
<td id="test" value="475"><button onclick="test()" id="btn1" aria-label="Happy Meal"></button></td>
<td id="test2" value="540">
<button onclick="test2()" id="btn2" aria-label="Big Mac"></button>
</td>
<td><button aria-label="All Products" id="logo" ></button></td>
<td><button id="btnClearEntry" onclick="clearentry()">CE</button></td>
</tr>
<tr>
<td id="test3" value="200"><button onclick="test3()" id="btn3" aria-label="Hamburger"></button></td>
<td id="test4" value="250"><button onclick="test4()" id="btn4" aria-label="6 Chicken Nuggets"></button></td>
<td id="test5" value="570"><button onclick="test5()" id="btn5" aria-label="Crispy Chicken Wrap"></button></td>
<td><button id="btnplus" onclick="add()"><b>+</b></button></td>
</tr>
<tr>
<td id="test6" value="350"><button onclick="test6()" id="btn6" aria-label="Big Fries"></button></td>
<td id="test7" value="430"><button onclick="test7()" id="btn7" aria-label="Blueberry Muffin"></button></td>
<td id="test8" value="190"><button onclick="test8()" id="btn8" aria-label="Coke"></button></td>
<td><button id="btnminus" onclick="sub()"><b>-</b></button></td>
</tr>
<tr>
<td id="test9" value="360"><button onclick="test9()" id="btn9" aria-label="Cesars salad"></button></td>
<td id="test10" value="290"><button onclick="test10()" id="btn10" aria-label="Egg McMuffin"></button></td>
<td id="test11" value="360"><button onclick="test11()" id="btn11" aria-label="Fish Mac"></button></td>
<td id="test12" value="490"><button onclick="test12()" id="btn12" aria-label="Royal with Cheese"></button></td>
</tr>
<tr>
<td></td>
<td id="test13" value="270"><button onclick="test13()" id="btn13" aria-label="Baked Apple Pie"></button></td>
<td id="test14" value="340"><button onclick="test14()" id="btn14" aria-label="Mc Sundae"></button></td>
<td></td>
</tr>
</table>
</div>
</div>
</body>
Here is a shorter version
I use the following techniques
unobtrusive event handler
object to hold the names and values
DOM manipulation (sorry I got lazy on the operators)
removed the button from the link and used an image instead for the logo
const buttons = {
"Happy Meal": 475,
"Big Mac": 540,
"Hamburger": 200,
"6 Chicken Nuggets": 250,
"Crispy Chicken Wrap": 570,
"Big Fries": 350,
"Blueberry Muffin": 430,
"Coke": 190,
"Cesars salad": 360,
"Egg McMuffin": 290,
"Fish Mac": 360,
"Royal with Cheese": 490,
"Baked Apple Pie": 270,
"Mc Sundae": 340
}
const operators = [
'<img src="http://www.mcdonalds.at/sites/default/files/cms/social_media/sharelogo.png" aria-label="All Products" id="logo" ></img>',
'<button id="btnClearEntry" onclick="clearentry()">CE</button>',
'<button id="btnplus" onclick="add()"><b>+</b></button>',
'<button id="btnminus" onclick="sub()"><b>-</b></button>'
]
const tb = document.querySelector(".calculator table tbody");
let cnt = 0;
let tr = document.createElement("tr");
for (let but in buttons) {
cnt++;
td = document.createElement("td");
td.innerHTML = '<button type="button" id="btn' + cnt + '" aria-label="' + but + '" value="' + buttons[but] + '"></button>';
tr.appendChild(td)
if (cnt % 3 === 0) {
if (operators.length > 0) {
td = document.createElement("td");
td.innerHTML = operators.shift()
}
tr.appendChild(td);
tb.appendChild(tr);
tr = document.createElement("tr");
}
}
tb.appendChild(tr);
tb.addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.type && tgt.type === "button") {
document.getElementById("txtResultItem").innerHTML = tgt.value;
}
});
function add() {
var y = document.getElementById("txtResultItem").innerHTML;
var z = document.getElementById("txtResult").innerHTML;
document.getElementById("txtResult").innerHTML = Number(y) + Number(z);
}
function sub() {
var y = document.getElementById("txtResultItem").innerHTML;
var z = document.getElementById("txtResult").innerHTML;
document.getElementById("txtResult").innerHTML = Number(z) - Number(y);
}
function clearentry() {
document.getElementById("txtResultItem").innerHTML = 0;
document.getElementById("txtResult").innerHTML = 0;
}
.main {
width: 100%;
height: 100vh;
background: linear-gradient(to right, rgba(26, 26, 43, 0.496), rgba(26, 26, 43, 0.86)), url("https://www.miss.at/wp-content/uploads/2019/11/Technik-Panne-McDonalds-muss-400.000-Euro-an-Gewinner-zahlen-1024x683.jpg");
background-position: center;
background-size: cover;
background-repeat: no-repeat;
display: flex;
justify-content: center;
align-items: center;
}
button {
height: 60px;
width: 60px;
border: 2px solid silver;
box-shadow: 2px 2px 5px black;
position: relative;
}
#txtResult {
width: 257px;
height: 40px;
text-align: right;
background: rgba(40, 40, 53, 0.69);
margin-bottom: 5px;
box-shadow: inset -2px -2px 1px gray;
}
#txtResultItem {
width: 257px;
height: 40px;
text-align: right;
background: rgba(40, 40, 53, 0.69);
margin-bottom: 5px;
box-shadow: inset -2px -2px 1px gray;
}
button {
height: 60px;
width: 60px;
background-size: contain;
}
#btnClearEntry {
font-family: 'Raleway';
max-height: 60px;
max-width: 60px;
}
#btn1 {
background-image: url("https://img.scoop.it/aImnklIQUA5uWH212vRoWjl72eJkfbmt4t8yenImKBVvK0kTmF0xjctABnaLJIm9");
}
#btn2 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-big-mac.png?$Nutritional_Desktop$");
}
#btn3 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-hamburger.png?$Nutritional_Desktop$");
}
#btn4 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-6-chicken-mcnuggets.png?$Nutritional_Desktop$");
}
#btn5 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-crispy-caesar-chicken-mcwrap.png?$Nutritional_Desktop$");
}
#btn6 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-fries-medium.png?$Nutritional_Desktop$");
}
#btn7 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-blueberry-muffin-hero.png?$Nutritional_Desktop$");
}
#btn8 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-coca-cola.png?$Nutritional_Desktop$");
}
#btn9 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-side-caesar-salad.png?$Nutritional_Desktop$");
}
#btn10 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-egg-mcmuffin.png?$Nutritional_Desktop$");
}
#btn11 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-filet-o-fish.png?$Nutritional_Desktop$");
}
#btn12 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-quarter-pounder-cheese.png?$Nutritional_Desktop$");
}
#btn13 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-baked-apple-pie.png?$Nutritional_Desktop$");
}
#btn14 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-hot-fudge-sundae.png?$Nutritional_Desktop$")
}
#logo {
height: 60px;
width: 60px;
border: 0px solid rgba(40, 40, 53, 0.89);
box-shadow: 2px 2px 9px black;
}
#btnClearEntry {
background: rgba(40, 40, 53, 0.79);
border: 1px solid white;
color: white;
width: 62px;
height: 62px;
box-shadow: 2px 2px 7px black;
}
#btnplus {
color: white;
background: red;
border: 1px solid silver;
font-size: 18px;
width: 60px;
height: 60px;
box-shadow: 2px 2px 7px black;
}
#btnminus {
color: white;
background: rgba(255, 223, 15, 1);
border: 1px solid silver;
font-size: 30px;
width: 60px;
height: 60px;
box-shadow: 2px 2px 7px black;
}
#logo {
border: 1px solid white;
}
.calculator {
box-shadow: 2px 2px 10 px rgba(0, 0, 0, 0.648);
padding: 5px;
}
button:hover {
position: relative;
}
button[aria-label]:hover:after {
content: attr(aria-label);
padding: 4px 8px;
position: absolute;
left: 0;
top: 100%;
white-space: nowrap;
z-index: 20;
background: red;
color: yellow;
font-family: 'Raleway';
}
<head>
<link rel="stylesheet" type="text/css" href="default.css">
<link href="https://fonts.googleapis.com/css?family=Raleway&display=swap" rel="stylesheet">
<script type="text/javascript" src="calc.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<div class="main">
<div class="calculator">
<table>
<tr>
<td colspan="4">
<div style="color:white; font-family:sans-serif;font-size:20px;" id="txtResult" readonly="readonly"></div>
</td>
</tr>
<tr>
<td colspan="4">
<div style="color:white; font-family:sans-serif;font-size:16px;" id="txtResultItem"></div>
</td>
</tr>
<tbody>
</tbody>
</table>
</div>
</div>
</body>
You can replace all of these functions with this;
function test(elementId){
var summe = document.getElementById("txtResult").innerHTML ;
var x = document.getElementById(elementId).getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
and then in your onClick handlers do something like
test('test')
test('test2')
test('test3')
and just pass in the id of the element as a string value to the function.
So, only variable among your functions is the id of the element from which you are getting x, you can write a function that accepts this variable as parameter and pass it to the function when calling it
function test(id){
var summe = document.getElementById("txtResult").innerHTML ;
var x = document.getElementById(id).getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
<button onclick="test('test')">
Try this , add an argument for a function with numerics as 1,2,3..etc and pass that value and append the same in the document.getElementById("test"+itemValue).getAttribute("value") value.
Dynamically pass the inputs from the click event.
function test(itemValue){
var summe = document.getElementById("txtResult").innerHTML ;
var x=document.getElementById("test"+itemValue).getAttribute("value");
document.getElementById("txtResultItem").innerHTML=x;
}
Check below snipet
function test(){
thisObj=event.target;
var summe = document.getElementById("txtResult").innerHTML ;
var x=thisObj.getAttribute("value");
document.getElementById("txtResultItem").innerHTML=x;
}
<div id="txtResult"></div>
<input type="button" value="1" onclick="test()" />
<input type="button" value="2" onclick="test()" />
<input type="button" value="3" onclick="test()" />
<div id="txtResultItem"></div>
You can use this reference at onclick event handler (without passing extra arguments like test3 etc)
function test(item){
console.log(item.value)
}
<div><button value="1" onclick="test(this)">1</button></div>
<div><button value="2" onclick="test(this)">2</button></div>
<div><button value="3" onclick="test(this)">3</button></div>
Or you can use event.target:
function test(){
var item = event.target;
console.log(item.value)
}
<div><button value="1" onclick="test()">1</button></div>
<div><button value="2" onclick="test()">2</button></div>
<div><button value="3" onclick="test()">3</button></div>
You can use a single function that passes in the id of the element you want to use as var x.
Javascript
function test_reuse(elid){
var summe = document.getElementById("txtResult").innerHTML ;
var x=document.getElementById(elid).getAttribute("value");
document.getElementById("txtResultItem").innerHTML=x;
}
Sample HTML element
<td id="test3" value="200"><button onclick="test_reuse('test3')" id="btn3" aria-label="Hamburger"></button></td>
You could have your buttons fire an event upon click, and given the event you can get the ID of the corresponding button and update the UI accordingly.
<td id="test3" value="200"><button onclick="test_general(event)" id="btn3" aria-label="Hamburger"></button></td>
....
//JS
function test_general(event){
var button_id = event.target.id
// DO SOMETHING NOW THAT YOU HAVE THE ID OF BUTTON
console.log(button_id)
}
Few pointers:
Having id on element can help you uniquely identify but the it becomes huge to keep track of. Use classes or composite selectors to achieve this.
Adding onClick on markup will pose a security threat as anyone can inspect your element and see whats going on. Using .addEventListener will encapsulate the code and keeps markup clean.
Having 1-1 mapping of button/ handler is an overkill. You can add any meta information as a part of data- tag and can be retrieved to process.
Following is the updated code: https://codepen.io/TBD007/pen/zYxgWbv which addresses above pointers.
Please note, I added data-number attribute in HTML

"float: left" div gets pushed down on input focus

I have the following form for lyrics upload. I've changed the design of the form a little bit, and now facing a weird problem.
I've created a fake-datalist using JS. On input focus, a fake-datalist (an ul element) is appended next to the input element. Its position is set to absolute so it shouldn't disrupt the flow of the document when it appears. However, it does. I can't seem to identify the problem. Once the datalist appears, the div next to the table gets pushed down. Table width isn't changing when the datalist appears, so it's not squizing the div and pushing it down.
Code Pen
var artists = [{"artist":"3 Doors Down"},{"artist":"5 Seconds of Summer"},{"artist":"Adele"},{"artist":"Alicia Keys"},{"artist":"Amanda Abizaid"},{"artist":"Avril Lavigne"}];
var albums = [{"album":"The Better Life","year":"2000","cover":"3_doors_down_2000_the_better_life.jpg"},{"album":"Away from the Sun","year":"2002","cover":"3_doors_down_2002_away_from_the_sun.jpg"},{"album":"Seventeen Days","year":"2005","cover":"3_doors_down_2005_seventeen_days.jpg"},{"album":"3 Doors Down","year":"2008","cover":"3_doors_down_2008_3_doors_down.jpg"},{"album":"Time of My Life","year":"2011","cover":"3_doors_down_2011_time_of_my_life.jpg"}];
var songs = [{"song":"Kryptonite","track_no":"1"},{"song":"Duck and Run","track_no":"3"},{"song":"Be Like That","track_no":"5"},{"song":"So I Need You","track_no":"11"}];
function datalist(element) {
return new datalist.prototype.init(element);
}
datalist.prototype = {
init: function(element) {
if (!element) {
this.element = document.createElement("ul");
this.element.classList.add("datalist");;
this.hide();
} else {
this.element = element;
}
},
update: function(queryElement) {
this.clear();
var lookUpArray = queryElement.name + "s";
var results = this.search(window[lookUpArray], queryElement.value, queryElement.name);
for (var i = 0; i < results.length; i++) {
var li = document.createElement("li");
var value = results[i][queryElement.name];
switch (queryElement.name) {
case "album":
li.setAttribute("data-year", results[i].year);
break;
case "song":
li.setAttribute("data-track_no", results[i].track_no);
break;
}
if (queryElement.value != "") {
var re = new RegExp(queryElement.value, "gi");
value = value.replace(re, "<span class=\"highlight\">" + "$&" + "</span>");
}
li.innerHTML = value;
this.element.appendChild(li);
}
return results.length;
},
search: function(lookUpArray, string, queryType) {
var results = [];
for (var i = 0; i < lookUpArray.length; i++) {
if (lookUpArray[i][queryType].toLowerCase().search(string.toLowerCase()) != -1) {
results.push(lookUpArray[i]);
}
}
return results;
},
clear: function() {
this.element.innerHTML = "";
},
hide: function() {
this.element.style.display = "none";
},
show: function() {
this.element.style.display = "";
},
remove: function() {
this.element.parentElement.removeChild(this.element);
},
for: function(sibling) {
sibling.parentElement.appendChild(this.element);
this.hide();
},
};
datalist.prototype.init.prototype = datalist.prototype;
var lastVisitedInput = null;
$("#lyrics-form").on("focus", "input.datalist-input", function() {
if (this.parentElement.children.length == 1) {
this.parentElement.appendChild(datalist().element);
}
if (lastVisitedInput) {
datalist(lastVisitedInput.nextElementSibling).hide();
}
lastVisitedInput = this;
if (datalist(this.nextElementSibling).update(this)) {
datalist(this.nextElementSibling).show();
} else {
datalist(this.nextElementSibling).hide();
}
});
$(document).on("click", function(e) {
if (lastVisitedInput) {
var exceptions = getExceptions(lastVisitedInput);
if (!contains(exceptions, e.target)) {
datalist(lastVisitedInput.nextElementSibling).remove();
lastVisitedInput = null;
}
}
});
$("#lyrics-form").on("input", "input.datalist-input", function() {
if (datalist(this.nextElementSibling).update(this)) {
datalist(this.nextElementSibling).show();
} else {
datalist(this.nextElementSibling).hide();
}
});
$("#lyrics-form").on("click", "li", function() {
this.parentElement.previousElementSibling.value = this.innerText;
$(this.parentElement.previousElementSibling).trigger("input");
});
function getRecord(input) {
var lookUpArray = window[input.name + "s"];
for (var i = 0; i < lookUpArray.length; i++) {
if (input.value == lookUpArray[i][input.name]) {
return lookUpArray[i];
}
}
return false;
}
function getExceptions(input) {
var exceptions = [
input,
input.nextElementSibling,
];
for (var i = 0; i < input.nextElementSibling.children.length; i++) {
exceptions.push(input.nextElementSibling.children[i]);
}
return exceptions;
}
function contains(array, item) {
for (var i = 0; i < array.length; i++) {
if (array[i] === item) {
return true;
}
}
return false;
}
* { margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline; } *, *:before, *:after { box-sizing: inherit; } body { line-height: 1.5; font-family: sans-serif; } input[type="button"], input[type="submit"] { cursor: pointer; } textarea, input[type="text"], input[type="search"], input[type="number"], input[type="password"] { border: 1px solid rgba(0,0,0,.2); padding: 4px; margin: 1px; } table { border-collapse: collapse; border-spacing: 0; }
body {
background-color: rgb(230, 230, 230);
font-family: Arial, sans-serif;
font-size: 14px;
color: rgba(0, 0, 0, .8);
box-sizing: border-box;
}
#main {
height: 500px;
background: white;
box-shadow: 0 0 2px rgba(0, 0, 0, .1), 0 2px 2px rgba(0, 0, 0, .1);
margin: 20px auto;
display: table;
padding: 20px;
}
#songInput {
overflow: auto;
}
#songTable td {
position: relative;
}
#songTable,
#coverDiv {
float: left;
}
#coverDiv {
margin-left: 20px;
}
#artist,
#album,
#song {
width: 250px;
}
#artist {
width: 300px;
width: 100%;
}
#year,
#track_no {
width: 70px;
}
#songTable td {
padding-bottom: 20px;
}
#songTable td:first-child {
padding-right: 10px;
}
#songTable .int-input {
padding-left: 20px;
padding-right: 10px;
}
#coverDiv > * {
display: block;
}
#coverDiv img {
width: 137px;
height: 137px;
border: 1px solid rgba(0, 0, 0, .2);
margin: 1px;
}
#coverUpload {
margin: 1px;
margin-top: 10px;
width: 250px;
}
#lyricsBox {
width: 100%;
height: 400px;
margin-top: 15px;
}
#submit {
width: 100%;
margin-top: 15px;
}
.datalist {
border: 1px solid silver;
box-shadow: 0 2px 5px rgba(0, 0, 0, .5);
position: absolute;
top: 32px;
left: 1px;
background: white;
padding: 5px;
max-height: 195px;
width: 180px;
width: 100%;
overflow-y: scroll;
z-index: 1000;
}
.datalist li {
padding: 2px 5px;
cursor: default;
}
.datalist li:hover {
background: rgba(0, 0, 0, .05);
color: black;
}
.datalist .highlight {
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">
<form action="addlyrics.php" id="lyrics-form" method="post" autocomplete="off" enctype="multipart/form-data">
<div id="songInput">
<table id="songTable">
<tr>
<td>Artist</td>
<td colspan="3">
<input type="search" name="artist" id="artist" class="datalist-input" placeholder="Artist" required />
</td>
</tr>
<tr>
<td>Album</td>
<td>
<input type="search" name="album" id="album" class="datalist-input" placeholder="Album" required />
</td>
<td class="int-input">Year</td>
<td>
<input type="number" name="year" id="year" class="input-num" placeholder="Year" required />
</td>
</tr>
<tr>
<td>Song</td>
<td>
<input type="search" name="song" id="song" class="datalist-input" placeholder="Name" required />
</td>
<td class="int-input">#</td>
<td>
<input type="number" name="track_no" id="track_no" class="input-num" placeholder="ID" required />
</td>
</tr>
</table>
<div id="coverDiv">
<img src="covers/blank.gif" id="cover" />
<input type="file" name="cover" id="coverUpload" accept="image/*" />
</div>
</div>
<textarea name="lyrics" placeholder="Lyrics" id="lyricsBox" /></textarea>
<input type="submit" id="submit" class="button" />
</form>
</div>
Removing overflow: auto; from #songInput, the parent element of the table and the div, solved the problem. Although, I don't understand why overflow: auto; on the parent would push the div down. Dynamically added ul.datalist's position is set to absolute, and when it appears, the only thing it might do is extend the height of the table, which shouldn't effect the div at the right.

Categories

Resources