Trigger function when a div enters another div - javascript

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

Related

Javascript eventlistener in loop function runs too many times

I have a couple of buttons which I'm trying to loop through and add a event listener function to them. I do this by using the following code:
function handleButtonClick({
target
}) {
const btnNode = target.closest('button');
console.log('hi')
}
const btns = document.querySelectorAll('.answerBtn');
btns.forEach(btns => {
btns.addEventListener('click', handleButtonClick)
})
Everytime a button is clicked it should run the function and it does. The only problem is that if I have 4 buttons, it runs the first button 4 time, the 2th button 3 times, the 3th button 2 times and the last ones. I know this happens because of the loop, but is there a way to make sure that it doesn't matter on what button I press, it only runs the function once?
let clickCountStorage = new Map;
class Question {
/**
* #param {string} question
* #param {string} prefix
* #param {string} description
* #param {string} display
* #param {string} answerType
* #param {string} multiSelect
* #param {Answer[]} answers
*/
constructor(question = "", prefix = "", description = "", display = "", answerType = "", multiSelect = "",
answers = []) {
this.question = question;
this.prefix = prefix;
this.description = description;
this.display = display;
this.answerType = answerType;
this.multiSelect = multiSelect;
this.answers = answers;
}
}
class Answer {
constructor(id = "", name = "") {
this.id = id;
this.name = name;
}
}
function createButton(id) {
let generateNewAnswer = document.createElement('button');
generateNewAnswer.setAttribute('type', 'button');
generateNewAnswer.id = `answerBtn${ id }`;
generateNewAnswer.classList.add('answerBtn');
generateNewAnswer.innerHTML = 'Add Answer';
return generateNewAnswer
}
function main() {
function handleButtonClick() {
let target = event.target;
const btnNode = target.closest('button');
const buttonClickTotal = clickCountStorage.get(btnNode) + 1;
clickCountStorage.set(btnNode, buttonClickTotal);
const clickCountList = Array
.from(
clickCountStorage.values()
);
const allButtonsClickTotal = clickCountList
.reduce((total, count) => total + count, 0);
const AllBtnsClickedThreeTimes = clickCountList
.every(count => count >= 3);
console.log({
buttonClickTotal,
allButtonsClickTotal,
AllBtnsClickedThreeTimes,
});
}
const btns = document.querySelectorAll('.answerBtn');
console.log(btns)
btns.forEach((btn) => {
btn.addEventListener('click', handleButtonClick);
console.log(btn)
})
}
class Structure {
constructor() {
/**
* #type {Question[]}
*/
this.questions = [];
this.clickCount = 0;
this.currentQuestion = this.questions.length;
this.displayArr = ["Selecteer soort:", "button", "colorBtn", "position", "dropdown"];
this.typeArr = ["Selecteer type:", "max", "all"];
this.MultiArr = ["Multiselect:", "true", "false"];
}
AddQuestion() {
let currentQuestion = this.questions.length;
// The new created question which has to be added to the questions.
let newQuestion = new Question();
// Push the new question to the question list.
this.questions.push(newQuestion);
// The div generator for the answers
let answerDIV = document.createElement('div');
answerDIV.className = 'answerDIV' + currentQuestion;
answerDIV.id = 'AnswerDivId' + currentQuestion;
document.getElementsByClassName('create')[0].appendChild(answerDIV);
let generateNewAnswer = createButton(currentQuestion);
clickCountStorage.set(generateNewAnswer, 0)
generateNewAnswer.onclick = _ => this.AddAnswer(currentQuestion);
document.getElementsByClassName('create')[0].appendChild(generateNewAnswer);
}
/**
* #param {int} workingQuestionIndex
*/
AddAnswer(workingQuestionIndex) {
let workingQuestion = this.questions[workingQuestionIndex];
let newAnswerIndex = workingQuestion.answers.length;
let newAnswerId = 'id' + newAnswerIndex;
// The new answer to insert.
let newAnswer = new Answer(newAnswerId);
// Add the new answer to the total answers.
workingQuestion.answers.push(newAnswer);
let idElement = document.createElement('input');
idElement.setAttribute('type', 'text');
idElement.name = "id";
idElement.id = newAnswerId;
idElement.classList.add('id', 'QuestionNumber' + workingQuestionIndex);
idElement.placeholder = 'Add the ID of the answer';
idElement.addEventListener('input', function(_) {
newAnswer.id = this.value;
});
// Appends the answers to the AnswerDiv
document.getElementsByClassName('answerDIV' + workingQuestionIndex)[0].appendChild(idElement);
}
}
class GenerateArray {
constructor() {
this.structure = new Structure();
}
generateQuestionPart() {
this.structure.AddQuestion();
}
}
let newQuestion = new Question();
let struc = new Structure();
NewArray = new GenerateArray();
document.querySelectorAll('.QPB')[0].addEventListener('click', () => {
main()
})
body {
margin: 0;
padding: 0;
}
.container {
height: 1000px;
width: 800px;
position: relative;
margin-top: 5px;
left: 50%;
-ms-transform: translate(-50%, 5%);
transform: translate(-50%, 5%);
}
.QPB {
position: relative;
float: left;
margin-left: 15px;
margin-top: 10px;
margin-bottom: 10px;
border: none;
border-radius: 0.25rem;
color: white;
font-size: 40px;
background-color: #ff5c01!important;
width: 50px;
height: 50px;
}
.question,
.prefix,
.description {
position: relative;
margin-right: 5px;
width: 95%;
height: 30px;
margin-bottom: 10px;
margin-left: 15px;
}
.SelClassD,
.SelClassT,
.SelClassM {
position: relative;
margin-right: 5px;
width: 20%;
height: 30px;
margin-bottom: 10px;
margin-left: 15px;
border: 2px solid #ced4da;
border-radius: 0.5rem;
}
.SelClassD:focus,
.SelClassT:focus,
.SelClassM:focus {
outline: none !important;
border: 4px solid rgb(135, 206, 250, 0.5);
border-radius: 0.5rem;
}
.question,
.description,
.prefix,
.id,
.name {
border: 2px solid #ced4da;
border-radius: 0.5rem;
}
.question:focus,
.description:focus,
.prefix:focus,
.id:focus,
.name:focus {
outline: none !important;
border: 4px solid rgb(135, 206, 250, 0.5);
border-radius: 0.5rem;
}
.id,
.name {
position: relative;
width: 90%;
height: 30px;
margin-bottom: 10px;
margin-left: 55px;
}
.answerBtn {
width: 100px;
height: 40px;
background-color: #ff5c01!important;
color: white;
border: none;
border-radius: 0.25rem;
margin-bottom: 50px;
margin-left: 15px;
}
.CreateArray {
width: 95%;
margin-left: 20px;
margin-bottom: 10px;
height: 40px;
background-color: #3db556!important;
color: white;
border: none;
border-radius: 0.25rem;
}
/* card */
.DONOT {
margin-left: 15px;
font-style: italic;
font-size: 24px;
}
.card-body-home {
border: 2px solid rgba(0, 0, 0, .125);
border-bottom: none;
border-radius: 3px 3px 0 0;
}
/* form card */
.form-card-DT {
max-width: 800px;
border: none!important;
height: 100%;
/* padding-bottom: 10px; */
}
.form-card-header {
border: none;
background-color: #ff5c01!important;
color: white;
font-weight: 500;
font-style: italic;
font-size: 24px;
padding-top: 10px;
padding-left: 15px;
border-radius: 0!important;
height: 35px;
}
.form-card-body {
border-radius: 0;
border: solid 1px #b5b5b5;
border-top: none;
}
<div style='width: 1000px;margin: auto;'>
<div class='card text-dark bg-light mb-3 form-card-DT'>
<div class='card-header form-card-header'>Creeër een vragenlijst:</div>
<div class='card-body form-card-body'>
<div class="DONOT">Gebruik het volgende teken niet ivm error: '</div>
<div class="create">
<button id="QuestionPartBtn" class="QPB" type="button" onclick="NewArray.generateQuestionPart()">+
</button>
<br><br>
</div>
<div class="result">
<button id="download-btn" class="CreateArray">Generate Code</button>
</div>
</div>
</div>
</div>
You can also try to use Event Bubbling and assign only one "click" event listener to the closest common parent

Does #id override the :hover change?

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

Javascript - I have two event listeners which run the same global scope function, but one of them isn't working...why?

For a bit of context, I'm currently new to Javascript and programming in general. I'm currently making a to-do list using vanilla javascript.
I want the user to be able to add an entry by either clicking on the "+" button, or by pressing the enter key in the input field.
Definitions:
let count = 0;
let getAdd = document.getElementById('add')
let getBackground = document.getElementById('background')
let getInputs = document.getElementsByClassName('input')
let getItems = document.getElementsByClassName('item')
let getName = document.getElementById('name')
The "keypress" event listener is working, but the "click" event listener is not. Here's the part in question:
function addevent() {
if (document.getElementById('name').value === '') {
alert("You need to type something in the input field first!")
return
}
if (getItems.length == 0) {
count += 1;
getBackground.innerHTML = ''
getBackground.style = null;
getBackground.innerHTML += '<div class="item"><div class="column input"></div><div id="spacer" class="column"></div><div id="bin" class="bin column row">X</div></div>'
getInputs[count - 1].innerHTML = document.getElementById('name').value
let heightplus = getBackground.offsetHeight;
getBackground.style.height = parseInt(heightplus + 35) + "px"
document.getElementById('name').value = ''
}
else {
count += 1
getBackground.innerHTML += '<div class="item"><div class="column input"></div><div id="spacer" class="column"></div><div id="bin" class="bin column row">X</div></div>'
getInputs[count - 1].innerHTML = document.getElementById('name').value
let heightplus = getBackground.offsetHeight;
getBackground.style.height = parseInt(heightplus + 35) + "px"
document.getElementById('name').value = ''
}
}
getAdd.addEventListener("click", addevent(), false);
getName.addEventListener("keypress", function enter(e) {
if (e.keyCode === 13) {
addevent();
}
}, false);
What am I missing here?
If you need any further info, let me know.
let count = 0;
let getAdd = document.getElementById('add')
let getBackground = document.getElementById('background')
let getInputs = document.getElementsByClassName('input')
let getItems = document.getElementsByClassName('item')
let getName = document.getElementById('name')
function noitems() {
if (count == 0) {
getBackground.innerHTML = '<div class="start">Click on the <strong>+</strong> button to get started</div>'
}
else if (count == -1) {
getBackground.innerHTML = '<div class="end">No more tasks? Happy days!</div>'
count += 1
}
getBackground.style.paddingTop = "0px"
getBackground.style.boxShadow = "0px 0px 0px 0px"
getBackground.style.backgroundColor = "white"
}
window.onload = noitems();
function addevent() {
if (document.getElementById('name').value === '') {
alert("You need to type something in the input field first!")
return
}
if (getItems.length == 0) {
count += 1;
getBackground.innerHTML = ''
getBackground.style = null;
getBackground.innerHTML += '<div class="item"><div class="column input"></div><div id="spacer" class="column"></div><div id="bin" class="bin column row">X</div></div>'
getInputs[count - 1].innerHTML = document.getElementById('name').value
let heightplus = getBackground.offsetHeight;
getBackground.style.height = parseInt(heightplus + 35) + "px"
document.getElementById('name').value = ''
}
else {
count += 1
getBackground.innerHTML += '<div class="item"><div class="column input"></div><div id="spacer" class="column"></div><div id="bin" class="bin column row">X</div></div>'
getInputs[count - 1].innerHTML = document.getElementById('name').value
let heightplus = getBackground.offsetHeight;
getBackground.style.height = parseInt(heightplus + 35) + "px"
document.getElementById('name').value = ''
}
}
getAdd.addEventListener("click", addevent(), false);
getName.addEventListener("keypress", function enter(e) {
if (e.keyCode === 13) {
addevent();
}
}, false);
function doSomething(e) {
if (e.target.id === "bin") {
if (getItems.length == 1) {
let clickeditem = e.target
getBackground.removeChild(clickeditem.parentNode)
count -= 2
noitems();
}
else {
let clickeditem = e.target
getBackground.removeChild(clickeditem.parentNode)
let heightminus = getBackground.offsetHeight;
getBackground.style.height = parseInt(heightminus - 75) + "px"
count -= 1
}
}
e.stopPropagation();
}
getBackground.addEventListener("click", doSomething, false)
#import url('https://fonts.googleapis.com/css2?family=Roboto:wght#100&display=swap');
body {
font-family: 'Roboto', sans-serif;
-webkit-touch-callout: none; /* iOS Safari */
-webkit-user-select: none; /* Safari */
-khtml-user-select: none; /* Konqueror HTML */
-moz-user-select: none; /* Old versions of Firefox */
-ms-user-select: none; /* Internet Explorer/Edge */
user-select: none; /* Non-prefixed version, currently
supported by Chrome, Opera and Firefox */
}
#title {
font-size: 32px;
margin-top: 1em;
border: 5px;
border-style: solid;
border-color: #001F5F;
width: 9em;
margin-left: calc(50% - 4.6em);
margin-right: calc(50% - 4.5em);
text-align: center;
}
#inputfield {
overflow: hidden;
padding-top: 5px;
padding-bottom: 5px;
margin-top: 50px;
margin-bottom: 10px;
}
::placeholder {
color: #E7E6E6;
opacity: 0.8;
}
#name {
height: 35px;
width: 813px;
outline: none;
background-color: #001F5F;
color: #E7E6E6;
text-align: left;
vertical-align: middle;
font-size: 22px;
box-shadow: 1px 2px 4px 2px darkgray;
margin-right: 10px;
border: 5px;
border-color: #E7E6E6;
float: left;
border-radius: 5px 5px 5px 5px;
}
#add {
height: 35px;
width: 35px;
background-color: #E7E6E6;
color: #001F5F;
font-size: 32px;
font-style: bold;
text-align: center;
vertical-align: middle;
line-height: 35px;
cursor: pointer;
box-shadow: 1px 2px 4px 2px darkgray;
float: left;
border-radius: 5px 5px 5px 5px;
}
#add:hover {
background-color:#001F5F;
color: #E7E6E6;
}
#background {
box-shadow: 0px 2px 4px 2px darkgray;
width: 900px;
height: 0px;
background-color: #E7E6E6;
padding-top: 20px;
border-radius: 5px 5px 5px 5px;
}
.start, .end {
text-align: center;
margin-top: 250px;
font-size: 32px;
padding: 0px;
vertical-align: middle;
}
#spacer {
width: 10px;
height: 35px;
background-color:#E7E6E6;
}
.input {
height: 35px;
width: 808px;
background-color:#001F5F;
padding-left: 5px;
border: 0px;
font-size: 22px;
color: #E7E6E6;
text-align: left;
vertical-align: middle;
outline: none;
box-shadow: 0px 2px 4px 2px darkgray;
border-radius: 5px 5px 5px 5px;
}
.bin {
width: 35px;
height: 35px;
font-size: 24px;
font-style: normal;
background-color: #E7E6E6;
color:#001F5F;
text-align: center;
vertical-align: middle;
line-height: 35px;
cursor: pointer;
border-radius: 5px 5px 5px 5px;
}
.bin:hover {
background-color:#001F5F;
color: #E7E6E6;
box-shadow: 0px 2px 4px 2px darkgray;
}
.item {
margin-left: 32px;
display: table;
table-layout: fixed;
width: 858px;
margin-bottom: 20px;
}
.column {
display: table-cell;
}
.thelist {
margin-left: calc(50% - 450px);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Oliver's To-Do List</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<h1 id="title">Oliver's To-Do List</h1>
<body>
<div class="thelist">
<div id="inputfield">
<input type="text" placeholder="Start typing here..."id="name">
<div id="add">+</div>
</div>
<div id="background">
</div>
</div>
<script src="main.js"></script>
</body>
</html>
Thanks!
getAdd.addEventListener("click", addevent(), false);
should be
getAdd.addEventListener("click", addevent, false);
As per this example from https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener :
// Function to change the content of t2
function modifyText() {
const t2 = document.getElementById("t2");
if (t2.firstChild.nodeValue == "three") {
t2.firstChild.nodeValue = "two";
} else {
t2.firstChild.nodeValue = "three";
}
}
// Add event listener to table
const el = document.getElementById("outside");
el.addEventListener("click", modifyText, false);
Ok so I found out that within the getAdd event listener, the problem was the pair of brackets after the function name; once these are removed, it works just fine!
If anyone reading wants to add to this with their wisdom, knowledge and experience, or perhaps suggest any other improvements, please do!
Thanks!
Oh, you solved it. I just tried it out and modified something in the index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Oliver's To-Do List</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<h1 id="title">Oliver's To-Do List</h1>
<body>
<div class="thelist">
<div id="inputfield">
<input type="text" placeholder="Start typing here..."id="name">
<div id="add" onclick="addevent()">+</div>
</div>
<div id="background">
</div>
</div>
<script src="main.js"></script>
</body>
</html>
I added onclick="addevent()" , and It works

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 can I remove all borders from a group of elements except for the one created?

I'm trying to dynamically make all borders disappear except the newest created container's border I have tried the commented out section of the JavaScript. Can someone please provide an explanation/example of how this can be done?
function countButtonLinks() {
var elementGroups = document.getElementById('containsAll');
if(elementGroups.children.length == 0) {
var numID = 1;
}
if(elementGroups.children.length == 1) {
var numID = 2;
}
if(elementGroups.children.length == 2) {
var numID = 3;
}
if(elementGroups.children.length == 3) {
var numID = 4;
}
if(elementGroups.children.length == 4) {
var numID = 5;
}
if(elementGroups.children.length == 5) {
var numID = 6;
}
return numID;
}
function createContainer() {
if(document.getElementById('containsAll').children.length < 6) {
var elementA = document.createElement("span");
var elementAInnerTxt = document.createElement("div");
elementA.id = 'elem' + countButtonLinks();
elementAInnerTxt.id = 'elemInner' + countButtonLinks();
elementA.className = 'elem1';
elementAInnerTxt.className = 'elemInner1';
elementA.appendChild(elementAInnerTxt);
document.getElementById('containsAll').appendChild(elementA);
}
}
.containsAll {
width: 91%;
height: 75%;
position: absolute;
float: left;
margin-top: 1%;
margin-left: 1%;
background-color: transparent;
z-index: 91;
border: 1px #000000 solid;
border-radius: 7px;
padding: 5px;
}
.elem1 {
max-width: 100%;
max-height: 100%;
min-width: 100px;
min-height: 60px;
float: left;
background-color: transparent;
border: 1px #333333 solid;
border-radius: 5px;
}
.elemInner1 {
max-width: 100%;
max-height: 100%;
min-width: 100px;
min-height: 60px;
float: left;
background-color: transparent;
padding: 5px;
}
.buttonClass {
width: 100px;
height: 50px;
}
<button class="buttonClass" type="button" onclick="createContainer();">Click Me</button>
<div id="containsAll" class="containsAll"></div>
Please, no JQuery.
function countButtonLinks(){
var elementGroups = document.getElementById('containsAll');
// you don't need to use 'var numID'
return elementGroups.children.length + 1;
}
function createContainer(){
if(document.getElementById('containsAll').children.length < 6){
// add code here
for(var i=0;i<document.getElementById('containsAll').children.length;i++){
document.getElementById('containsAll').children[i].style.border = '0 none';
}
var elementA = document.createElement("span");
//...
Simply call the existing children of the element and remove the border before inserting
another element:
function countButtonLinks(){
var elementGroups = document.getElementById('containsAll');
var groupLength = elementGroups.children.length;
return groupLength++;
}
function createContainer() {
var containsAll = document.getElementById('containsAll'),
childrenLength = containsAll.children.length;
if (childrenLength >= 6) {
return; // Bail immediately since we only need to add a new element if the children's length is less than 6
}
// Call previous children
for ( var i = 0; i < childrenLength; i++ ) {
let child = containsAll.children[i];
// You can add a new class here that will remove the border
// but in this example, we'll use the style attribute to remove the border
child.style.border = 0;
}
// Now, add the new element
var elementA = document.createElement("span");
var elementAInnerTxt = document.createElement("div");
elementA.id = 'elem' + countButtonLinks();
elementAInnerTxt.id = 'elemInner' + countButtonLinks();
elementA.className = 'elem1';
elementAInnerTxt.className = 'elemInner1';
elementA.appendChild(elementAInnerTxt);
containsAll.appendChild(elementA);
}
Also, if you're going to use an element multiple times inside a function, make it a habit to store that element in a variable so you don't repeatedly calls the document.getElementById function.
You can accomplish this using the CSS :last-child selector
var container = document.getElementById('container');
function count_button_links()
{
return container.children.length + 1;
}
function new_container()
{
if (count_button_links() > 6) return false;
let span = document.createElement('span');
span.id = 'el_' + count_button_links();
span.className = 'box';
container.appendChild(span);
}
#container {
width: 100%;
background-color: transparent;
border: 1px solid #000;
border-radius: 7px;
padding: 5px;
display:flex;
height:200px;
}
.box {
flex:0 0 100px;
height:60px;
background-color: transparent;
border-radius: 5px;
}
.box:last-child{
border:1px solid #333;
}
button {
width: 100px;
height: 50px;
}
<button type="button" onclick="new_container();">Click Me</button>
<div id="container"></div>

Categories

Resources