How can I execute a function without an event? - javascript

Solved by # epascarello
Have to execute function without event so that discount can be displayed along with prices at the start without clicking or any other event
You can see in below snippet that 1st one is running automatic while 2nd one is running on click . Can it possible to run 2nd one as automatic because it solves my most of issues using this keyword
Let me know if you need clarification . Any suggestion or comments will be helpful.
function discount1() {
var sendTotal = document.getElementsByClassName("TotalPrice1")[0].innerHTML;
var send1 = sendTotal.replace(/₹/gi, "");
var send2 = send1.replace(/,/gi, "");
var send3 = Number(send2)
var send = document.getElementsByClassName("DiscPrice1")[0].innerHTML;
var send4 = send.replace(/₹/gi, "");
var send5 = send4.replace(/,/gi, "");
var send6 = Number(send5)
var rest = ((send3 - send6) / send3) * 100
document.getElementsByClassName("demo1")[0].innerHTML = rest.toFixed(0) + "% off";
}
discount1();
function discount(rest) {
var sendTotal = rest.parentElement.getElementsByClassName("TotalPrice")[0].innerHTML;
var send1 = sendTotal.replace(/₹/gi, "");
var send2 = send1.replace(/,/gi, "");
var send3 = Number(send2)
var send = rest.parentElement.getElementsByClassName("DiscPrice")[0].innerHTML;
var send4 = send.replace(/₹/gi, "");
var send5 = send4.replace(/,/gi, "");
var send6 = Number(send5)
var rent = ((send3 - send6) / send3) * 100
rest.getElementsByClassName("demo")[0].innerHTML = rent.toFixed(0) + "% off";
}
<div>
<div class="seen" onclick="discount1()">
<div class="TotalPrice1">₹9,728</div>
<div class="DiscPrice1">₹5,435</div>
<div class="demo1"></div>
</div>
</div>
<br>
<div>
<div class="seen" onclick="discount(this)">
<div class="TotalPrice">₹15,670</div>
<div class="DiscPrice">₹13,785</div>
<div class="demo"></div>
</div>
</div>

So you need to call your function with the element.
How you get the elements is up to you. querySelectorAll, getElementsByClassName, ids, etc.
function discount () { /*...*/ }
document.querySelectorAll(".daad").forEach(discount);
you can do it inside of the function
function discount () {
document.querySelectorAll(".daad").forEach(function (reed) {
var saadTotal = reed.parentElement.getElementsByClassName("Total")[0].innerHTML;
console.log('saadTotal', saadTotal);
var saadTotal2 = reed.querySelector(".Total").textContent;
console.log('saadTotal2', saadTotal2);
}
}
discount();

This is answer for previous question you can see in question edits
This is what I needed to do show discount percentage without any event (like onclick or onload) . You can see in below snippet .
function discount(rest) {
var sendTotal = rest.parentElement.getElementsByClassName("TotalPrice")[0].innerHTML;
var send1 = sendTotal.replace(/₹/gi, "");
var send2 = send1.replace(/,/gi, "");
var send3 = Number(send2)
var send = rest.parentElement.getElementsByClassName("DiscPrice")[0].innerHTML;
var send4 = send.replace(/₹/gi, "");
var send5 = send4.replace(/,/gi, "");
var send6 = Number(send5)
var rent = ((send3 - send6) / send3) * 100
rest.getElementsByClassName("demo")[0].innerHTML = rent.toFixed(0) + "% off";
}
document.querySelectorAll(".seen").forEach(discount);;
<div>
<div class="seen" onclick="discount(this)">
<div class="TotalPrice">₹9,728</div>
<div class="DiscPrice">₹5,435</div>
<div class="demo"></div>
</div>
</div>
<br>
<div>
<div class="seen" onclick="discount(this)">
<div class="TotalPrice">₹15,670</div>
<div class="DiscPrice">₹13,785</div>
<div class="demo"></div>
</div>
</div>

Related

Attaching Event to dynamically created element

I am working at my 'To Do List'. My goal is to create an 'delete' button inside previously created div, which contains note written by user.
The problem is that I can't use Jquery - click() because it doesn't work with dynamically created elements.
I tried to use on(), but it causes that 'delete' button appears in every note I made.
var ammleng;
var amount = [];
function ammcheck() {
if (amount.length == 0) {
return amount.length;
} else {
return amount.length++;
}
}
function Start() {
var start = document.getElementsByClassName('start')[0];
start.style.display = 'none';
var textarea = document.getElementsByClassName('textarea')[0];
textarea.classList.remove('locked');
var btn = document.getElementsByClassName('btn__container')[0];
btn.classList.remove('locked');
var text = document.getElementsByClassName('text')[0];
text.classList.add('after');
$('.notes').slideDown(2000);
}
function add() {
var txtarea = document.getElementsByClassName('textarea')[0];
ammleng = amount.length;
if (ammleng >= 13) {
alert('Za dużo notatek!')
} else if (txtarea.innerText.length < 1) {
alert('Nic nie napisałeś :(');
} else {
amount[ammcheck()] = document.getElementsByClassName('note');
var text = $('.textarea').html();
var cont = document.getElementsByClassName('notes')[0];
var ad = document.createElement('div');
var adding = cont.appendChild(ad);
adding.classList.add('note');
adding.innerText = text;
txtarea.innerText = '';
}
}
function reset() {
var els = document.getElementsByClassName('notes')[0];
els.innerHTML = '';
amount = [];
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='content'>
<div class='logo'>
To Do List
</div>
<div class='text'>
<button class='start' onclick='Start()'>Zaczynajmy</button>
<div class='textarea locked' contenteditable='true' data-text='Wpisz notkę...'></div>
<div class='btn__container locked'>
<button class='dodaj' onclick='add()'>Dodaj</button>
<button class='resetuj' onclick='reset()'>resetuj</button>
</div>
</div>
<div class='notes'></div>
</div>
I tried to make it this way, but it return an error (...'appendChild() is not a function...')
var del = document.createElement('div');
del.classList.add('del');
$('.notes').on('click', '.note', function(){
$(this).appendChild(del);
})
use already existing document to bind click on
$(document).on('click', '.note', function(){
$(this).appendChild(del);
})

Custom id's in javascript created elements

So I am working on a jeopardy web app and I have a portion of the app where players can create as many teams as they need and give them a custom name.
HTML
<!--Score Boards-->
<div id="teamBoards">
<div id="teams">
</div>
<div id="addTeams">
<h3>Add Teams</h3>
<input type="text" placeholder="Enter Team Name" id="teamName">
<button id="addTeam">Add a Team</button>
</div>
</div>
JS
var div = document.createElement("div");
div.className = "Teams"
var teamNameElement = document.createElement("h3");
var teamName = $('#teamName').val();
teamNameElement.textContent = teamName;
var score = document.createElement("h4");
score.textContent = "0";
score.id = "score"+teamName;
score.className = "score";
var plusButton = document.createElement("button");
plusButton.textContent = "+";
plusButton.id = "plus"+teamName;
plusButton.className = "plus";
var minusButton = document.createElement("button");
minusButton.textContent = "-";
minusButton.id = "minus"+teamName;
minusButton.className = "minus";
div.appendChild(teamNameElement);
div.appendChild(score);
div.appendChild(plusButton);
div.appendChild(minusButton);
var placementDiv = document.getElementById('teams');
placementDiv.appendChild(div);
The code above creates a team name, a place for the score with 0 preset, and a plus and minus button for points.
I start to have trouble when I go to add or subtract points by 100.
JS
$(plusButton).on('click', add);
$(minusButton).on('click', minus);
function add(){
var score1 = $('.score').html();
console.log(score1);
score1 = Number(score1);
score1 = score1 + 100;
console.log(score1);
$(score).html(score1);
}
function minus(){
var score1 = $('.score').html();
score1 = Number(score1);
score1 = score1 - 100;
$(score).html(score1);
}
All of the code here is in one function, so some variables from the plus and minus functions could be the variables from the code above. The problem is that I can not add points to specific teams' scoreboard through a specific id for each team score.
Here is a way to do what your looking at using more jQuery and $this selectors to work with individual teams like you want. I added some notes in the snippet below. Just run the snippet a few times and look at the comments to see how the teams are being selected.
$(function(){
var teamCount = 0;
var $teamsDiv = $("#teams");
$("#addTeam").click(function(){
//get the team name value
var teamName = $("#teamName").val();
//Create clone of html team template
var $newTeam = $("#teamTemplate").clone();
//Set an id for each team using the teamCount var
$newTeam.attr("id", "team" + teamCount);
//Set the entered text
$newTeam.find(".teamName").text(teamName);
//Set the score to zero
$newTeam.find(".score").text("0");
//Append new team to teams div
$teamsDiv = $("#teams");
$teamsDiv.append($newTeam.html());
});
//Add button press (using $("#teams").on('click'... allows for setting
//listeners on dynamically created html
$("#teams").on('click', '.plusButton', function() {
var $teamTemplate = $(this).closest(".template");
var $score = $teamTemplate.find(".score");
var teamName = $teamTemplate.find(".teamName").text();
var currentScore = parseInt($score.text());
$score.text(currentScore + 100);
$(this).closest(".template").find(".teamName");
console.log(teamName + " Score: " + $score.text());
})
//Minus button press
$("#teams").on('click', '.minusButton', function() {
//Using the "this" selector edit just the div you want.
var $teamTemplate = $(this).closest(".template");
var $score = $teamTemplate.find(".score");
var teamName = $teamTemplate.find(".teamName").text();
var currentScore = parseInt($score.text());
//Set new score text
$score.text(currentScore - 100);
//Console.log just to see what is happening
$(this).closest(".template").find(".teamName");
console.log(teamName + " Score: " + $score.text());
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!--Score Boards-->
<div id="teamBoards">
<div id="addTeams">
<h3>Add Teams</h3>
<input type="text" placeholder="Enter Team Name" id="teamName">
<button id="addTeam">Add a Team</button>
</div>
<br />
<div id="teams">
</div>
</div>
<div style="display:none;" id="teamTemplate" >
<div class="template">
<span class="teamName"></span>
<button class="plusButton" type="button">+</button>
<button class="minusButton">-</button>
<span class="score">0</span>
<br />
</div>
</div>
I would highly recommend the Jquery video tutorial for getting a jump on using jQuery. It is a great tutorial that shows all the tricks to making client side code quick and easy.

get a new value input .innerHTML

I'm having some problem understanding how to get a new value from my span id='savings'. As you can see I need to make my bank account works. if a deposit is all good, but when I want to withdraw some money it starts from my starting point of 0, instead of starting from what I deposited.
var inputAmount = document.getElementById('inputAmount');
var withdBtn = document.getElementById('withdBtn');
var savingSpan = document.querySelector('#savings');
var myBalance = Number(savingSpan.innerHTML);
var depBtn = document.getElementById('depBtn');
depBtn.addEventListener('click', function() {
var savAmount = Number(inputAmount.value);
var depositBalance = savAmount + myBalance;
savingSpan.innerHTML = depositBalance;
});
withdBtn.addEventListener('click', function() {
var savAmount = Number(inputAmount.value);
var withdrawBalance = (myBalance.innerHTML) - savAmount;
savingSpan.innerHTML = withdrawBalance;
});
<h1></h1>
<div class="savings" id="accounts">
<h2>Savings Account</h2>
<h3> Your current balance is </h3>
<span>$</span> <span id="savings"> 00.00 </span>
<p>
<input id="inputAmount" type="number" placeholder="Enter amount here">
</p>
<p>
<button id="withdBtn" type="button">Withdraw</button>
<button id="depBtn" type="button">Deposit</button>
</p>
</div>
There are two mistakes in your code:
You're calling myBalance.innerHTML, but it should just be myBalance as this variable is already holding the value.
You need to update you myBalance variable when the buttons are clicked. Currently the
Simple solution: Just replace depositBalance and withdrawBalance with myBalance.
depBtn.addEventListener('click', function() {
var savAmount = Number(inputAmount.value);
myBalance = savAmount + myBalance;
savingSpan.innerHTML = myBalance;
});
withdBtn.addEventListener('click', function(){
var savAmount = Number(inputAmount.value);
myBalance = myBalance - savAmount;
savingSpan.innerHTML = myBalance;
});
See also https://jsfiddle.net/enpo/wdu87Lek/.
You need to switch myBalance with savingSpan in the withBtn function. myBalance is a number and therefore doesn't have the attribut innerHTML
withdBtn.addEventListener('click', function() {
var savAmount = Number(inputAmount.value);
var withdrawBalance = (savingSpan.innerHTML) - savAmount;
savingSpan.innerHTML = withdrawBalance;
});
EDIT:
For multiple deposits, you also need to replace myBalance with Number(savingSpan.innerHTML) in the depBtn function. myBalance only gets sets once at the beginning and therefore doesn't represent the current balance.
depBtn.addEventListener('click', function() {
var savAmount = Number(inputAmount.value);
var depositBalance = savAmount + Number(savingSpan.innerHTML);
savingSpan.innerHTML = depositBalance;
});

Why does my value keep returning as "NaN"?

Here is the link to the jsbin.
I was almost finished with my project (I thought I was) and then I tested it out. It is supposed to add buttons with the chosen title of the task and the number of points it awards. Every time the button is clicked the points would be added on to the "Points" section and every 500 points my "Level" would increase.
Upon finishing it, it worked. Then I went to clear the localStorage since that's what I used to save the information, but I wanted to start over. When I did that, the 'Points' section, or 'results' value, keeps returning as "NaN". The code is exactly the same as it was when it worked. Can someone please tell me how to fix this problem, thank you in advance.
Here is the code. (Used bootstrap for CSS)
HTML
<center>
<br>
<h2> Add task </h2>
<div class='well' style='width:500px' id="addc">
<div id="addc">
<input class='form-control' style='width:450px' id="btnName" type="text" placeholder="New Task" /><br>
<input class='form-control' style='width:450px' id="btnPoints" type="text" placeholder="Points" /><br>
<button id="addBtn">Add</button>
</div> </div>
<div class='well' style='width:230px' id="container">
</div>
<hr style="width:400px;">
<h3>Points </h3>
<div id="result">0</div>
</div>
<hr style="width:400px;">
<div style="width:400px;">
<h3>Level
<p id='lvl'>0</p>
</div>
<hr style="width:400px;">
</center>
JavaScript
var res = document.getElementById('result');
res.innerText = localStorage.getItem('myResult');
var level = document.getElementById('lvl');
level.textContent = localStorage.getItem('myLevel');
var btns = document.querySelectorAll('.btn');
for(var i = 0; i < btns.length; i++) {
btns[i].addEventListener('click', function() {
addToResult(this.getAttribute('data-points'));
this.parentNode.removeChild(this.nextElementSibling);
this.parentNode.removeChild(this);
});
}
var addBtn = document.getElementById('addBtn');
addBtn.className = "btn btn-default";
addBtn.addEventListener('click', function() {
var container = document.getElementById('container');
var btnName = document.getElementById('btnName').value;
var btnPoints = parseInt(document.getElementById('btnPoints').value);
if(!btnName)
btnName = "Button ?";
if(!btnPoints)
btnPoints = 50;
var newBtn = document.createElement('button');
var newPnt = document.createElement('span');
newBtn.className = 'btn btn-danger';
newBtn.innerText = btnName;
newBtn.setAttribute('data-points', btnPoints);
newBtn.addEventListener('click', function() {
addToResult(this.getAttribute('data-points'));
this.parentNode.removeChild(this.nextElementSibling);
this.parentNode.removeChild(this);
});
newPnt.className = 'label';
newPnt.innerText = "+" + btnPoints;
container.appendChild(newBtn);
container.appendChild(newPnt);
});
function addToResult(pts) {
var result = document.getElementById('result');
result.innerText = parseInt(result.innerText) + parseInt(pts);
var lvl = 0;
var a = 100;
while (result.innerText > 5*a) {
lvl+=1;
a+=100;
}
document.getElementById('lvl').innerText = lvl;
var res = document.getElementById('result');
localStorage.setItem("myResult", res.innerText);
var level = document.getElementById('lvl');
localStorage.setItem("myLevel", level.textContent);
}
You were parsing result.innerText as a number, but its value, initially, was actually either NaN or nothing, both which end up being NaN. One fix is to just check if it parsed to a number, and if it didn't, fall back to 0.
I just basically changed that and removed some getElementByIds that, in my opinion, were redundant, check the addToResult function:
http://jsfiddle.net/owc26a0p/1/
function addToResult(pts) {
// NaN is falsy, so you can just use || to make a fallback to 0
var result = parseInt(resDiv.innerText, 10) || 0,
lvl = 0,
a = 100;
result = result + parseInt(pts, 10) || 0;
while (result > 5 * a) {
lvl += 1;
a += 100;
}
resDiv.innerText = result;
levelDiv.innerText = lvl;
localStorage.setItem("myResult", result);
localStorage.setItem("myLevel", levelDiv.textContent);
}
I ended up using jsFiddle since I couldn't always get jsBin to save my changes. Good luck.

How can I copy this function but with preset values?

Currently when a button is clicked, it subtracts an inputted value. I want to have a preset value subtracted once a preset button is clicked. It would also be perferable that I could reuse a function later on a different button with different values like so:
var preset = function(val1, val2, val3, val4) {
//function to subtract from current values
}
$('presetButton').click(function(){
preset(1,2,3,4)
}
Here is the current function as I have it. The first button function works, but I wanted to copy it into a preset button with preset values. The function would not include $(this) because the button would not be in the same wrapper div and are not siblings.
$(document).ready(function(){
$('button').click(function(){
var $button = $(this);
var subtract = parseInt($button.siblings('input').val(), 10);
var $currentP = $button.siblings('.number').children('p');
var current = parseInt($currentP.text(), 10);
var newVal = current - subtract;
var $history = $button.siblings('.wrap').children('.history');
if (isNaN(subtract)) {
alert("Please enter in a number");
} else {
$currentP.effect('bounce', function() {
$currentP.text(newVal);
$(this).show();
});
$history.append("<p>"+subtract+"</p>");
}
});
$('#presets').click(function(){
//set up the subtracting and current variables
var subCal = 120;
var subPro = 24;
var subCarbs = 3;
var subFat = 1;
//retrieve current number then convert to a number
var toNum = function(id) {
return parseInt($(id + ' .number').children('p').text(), 10);
}
var curCal = toNum('#calories');
var curPro = toNum('#protein');
var curCarbs = toNum('#carbs');
var curFat = toNum('#fats');
//create new values
var newCal = curCal - subCal;
var newPro = curPro - subPro;
var newCarbs = curCarbs - subCarbs;
var newFat = curFat - subFat;
//apply new values
var applyNew = function(id, newVal) {
$(id + ' .number p').text(newVal)
}
applyNew('#calories', newCal);
applyNew('#protein', newPro);
applyNew('#carbs', newCarbs);
applyNew('#fats', newFats);
//Add to presets to history
})
});
The HTML
<h1>Track your Macros</h1>
<div class="wrapper">
<div id="calories">
<div class="number"><p>1945</p></div>
<div class="label"><p>Calories</p></div>
<input type="text"></input>
<button>Subtract</button>
<div class="wrap">
<div class="history"></div>
</div>
</div>
<div id="protein">
<div class="number"><p>200</p></div>
<div class="label"><p>Protein</p></div>
<input type="text"></input>
<button>Subtract</button>
<div class="wrap">
<div class="history"></div>
</div>
</div>
<div id="carbs">
<div class="number"><p>173</p></div>
<div class="label"><p>Carbs</p></div>
<input type="text" class="subtract"></input>
<button>Subtract</button>
<div class="wrap">
<div class="history"></div>
</div>
</div>
<div id="fats">
<div class="number"><p>50</p></div>
<div class="label"><p>Fats</p></div>
<input type="text" class="subtract"></input>
<button>Subtract</button>
<div class="wrap">
<div class="history"></div>
</div>
</div>
</div>
<div id="presets"><img src="on-logo.png"></div>
Try
$(document).ready(function(){
$('button').click(function(){
var $button = $(this);
var subtract = parseInt($button.siblings('input').val(), 10);
var $currentP = $button.siblings('.number').children('p');
var current = parseInt($currentP.text(), 10);
var newVal = current - subtract;
var $history = $button.siblings('.wrap').children('.history');
if (isNaN(subtract)) {
alert("Please enter in a number");
} else {
$currentP.effect('bounce', function() {
$currentP.text(newVal);
$(this).show();
});
$history.append("<p>"+subtract+"</p>");
}
});
var preset = function(val1, val2, val3, val4) {
//set up the subtracting and current variables
var subCal = val1;
var subPro = val2;
var subCarbs = val3;
var subFat = val4;
//retrieve current number then convert to a number
var toNum = function(id) {
return parseInt($(id + ' .number').children('p').text(), 10);
}
var curCal = toNum('#calories');
var curPro = toNum('#protein');
var curCarbs = toNum('#carbs');
var curFat = toNum('#fats');
//create new values
var newCal = curCal - subCal;
var newPro = curPro - subPro;
var newCarbs = curCarbs - subCarbs;
var newFats = curFat - subFat;
//apply new values
var applyNew = function(id, newVal) {
$(id + ' .number p').text(newVal);
}
//apply new values
var applyHistory = function(id, val) {
$(id + ' .history').append("<p>" + val + "</p>");
}
applyNew('#calories', newCal);
applyNew('#protein', newPro);
applyNew('#carbs', newCarbs);
applyNew('#fats', newFats);
applyHistory('#calories', subCal);
applyHistory('#protein', subPro);
applyHistory('#carbs', subCarbs);
applyHistory('#fats', subFat);
}
$('#presets').click(function(){
preset(120,24,3,1);
})
});
Demo: Fiddle

Categories