How do I add new text after all functions are executed? - javascript

I want to have a line of text "oh no you are staving" to show up only after all items are removed. So in this case it means all the function are executed. Do I have to create a if statement?
Sorry I am really new to programming so I know my code is very wonky. Thanks for helping still!
function ateKroket() {
var delFood = document.getElementById("kroket");
delFood.remove();
}
function ateCake() {
var delFood = document.getElementById("cake");
delFood.remove();
}
function atePizza() {
var delFood = document.getElementById("pizza");
delFood.remove();
}
function ateSushi() {
var delFood = document.getElementById("sushi");
delFood.remove();
}
<div id="foodStorage">
<div id="kroket">
<img class="foodImg" src= "images/kroket.jpg">
<div><h5 id="foodName">Kroket</h5>
<button class="ateBtn" onclick="ateKroket()">Ate</button>
</div>
</div>
<div id="cake">
<img class="foodImg" src= "images/cake.jpg">
<div><h5 id="foodName">Cake</h5>
<button class="ateBtn" onclick="ateCake()">Ate</button>
</div>
</div>
<div id="pizza">
<img class="foodImg" src= "images/pizza.jpg">
<div><h5 id="foodName">Pizza</h5>
<button class="ateBtn" onclick="atePizza()">Ate</button>
</div>
</div>
<div id="sushi">
<img class="foodImg" src= "images/sushi.jpg">
<div><h5 id="foodName">Sushi</h5>
<button class="ateBtn" onclick="ateSushi()">Ate</button>
</div>
</div>

Add the following:
(To HTML):
<div id="foodEaten" style="display:none;">4</div>
(Then to your Javascript):
function ateKroket() {
var delFood = document.getElementById("kroket");
delFood.remove();
checkFood()
}
function ateCake() {
var delFood = document.getElementById("cake");
delFood.remove();
checkFood()
}
function atePizza() {
var delFood = document.getElementById("pizza");
delFood.remove();
checkFood()
}
function ateSushi() {
var delFood = document.getElementById("sushi");
delFood.remove();
checkFood()
}
function checkFood(){
var foodLeft = parseInt(document.getElementById('foodEaten').innerHTML);
foodLeft = foodLeft-1;
document.getElementById('foodEaten').innerHTML = foodLeft;
if(foodLeft<1){
console.log("starving");
//DO WHATEVER YOU WANT WHEN NO FOOD LEFT
}
}
What this will do is edit an invisible counter of food left each time a button is clicked, and then action something if that counter is a certain value

You should make use of classes to make your code more maintainable/reusable wihout repetition. Here is an example where I added a food class to each food div:
var foodStorage = document.getElementById('foodStorage'),
ateBtns = document.querySelectorAll('.ateBtn');
ateBtns.forEach(function(btn) {
btn.addEventListener('click', function() {
foodStorage.removeChild(this.closest('.food'));
if (foodStorage.children.length === 0) {
alert('Oh no, you are starving!');
}
});
});
<div id="foodStorage">
<div class="food">
<div><h5>Kroket</h5>
<button class="ateBtn">Ate</button>
</div>
</div>
<div class="food">
<div><h5 id="foodName">Cake</h5>
<button class="ateBtn">Ate</button>
</div>
</div>
<div class="food">
<div><h5>Pizza</h5>
<button class="ateBtn">Ate</button>
</div>
</div>
<div class="food">
<div><h5>Sushi</h5>
<button class="ateBtn">Ate</button>
</div>
</div>
</div>

You could declare a variable counter:
var food = 4;
function ateKroket() {
var delFood = document.getElementById("kroket");
delFood.remove();
checkfood()
}
function ateCake() {
var delFood = document.getElementById("cake");
delFood.remove();
checkfood()
}
function atePizza() {
var delFood = document.getElementById("pizza");
delFood.remove();
checkfood()
}
function ateSushi() {
var delFood = document.getElementById("sushi");
delFood.remove();
checkfood()
}
function checkfood() {
food--;
if (food === 0) {
document.getElementById("starving").style.display = "block";
}
}
#starving {
display: none;
}
<div id="foodStorage">
<div id="kroket">
<img class="foodImg" src="images/kroket.jpg">
<div>
<h5 id="foodName">Kroket</h5>
<button class="ateBtn" onclick="ateKroket()">Ate</button>
</div>
</div>
<div id="cake">
<img class="foodImg" src="images/cake.jpg">
<div>
<h5 id="foodName">Cake</h5>
<button class="ateBtn" onclick="ateCake()">Ate</button>
</div>
</div>
<div id="pizza">
<img class="foodImg" src="images/pizza.jpg">
<div>
<h5 id="foodName">Pizza</h5>
<button class="ateBtn" onclick="atePizza()">Ate</button>
</div>
</div>
<div id="sushi">
<img class="foodImg" src="images/sushi.jpg">
<div>
<h5 id="foodName">Sushi</h5>
<button class="ateBtn" onclick="ateSushi()">Ate</button>
</div>
</div>
<div id="starving">
oh no you are starving
</div>
</div>
Or something much more optimized:
document.getElementById("foodStorage").addEventListener("click", function(e) {
if (e.target.classList.contains("ateBtn")) {
e.target.parentElement.parentElement.remove();
if (this.childElementCount === 1) {
document.getElementById("starving").style.display = "block";
}
}
});
#starving {
display: none;
}
<div id="foodStorage">
<div id="kroket">
<img class="foodImg" src="images/kroket.jpg">
<div>
<h5 id="foodName">Kroket</h5>
<button class="ateBtn">Ate</button>
</div>
</div>
<div id="cake">
<img class="foodImg" src="images/cake.jpg">
<div>
<h5 id="foodName">Cake</h5>
<button class="ateBtn">Ate</button>
</div>
</div>
<div id="pizza">
<img class="foodImg" src="images/pizza.jpg">
<div>
<h5 id="foodName">Pizza</h5>
<button class="ateBtn">Ate</button>
</div>
</div>
<div id="sushi">
<img class="foodImg" src="images/sushi.jpg">
<div>
<h5 id="foodName">Sushi</h5>
<button class="ateBtn">Ate</button>
</div>
</div>
<div id="starving">
oh no you are starving
</div>
</div>

Related

How to I replace these two buttons with a text in Javascript

I have these two buttons ACCEPT/DECLINE friend request
How do I replace them with the text "You accepted X's friend request" if you click the Accept button and with the "You declined X's friend request" if you click on the Decline button? I know I should add an eventlistener to it.
const acceptRequest = document.getElementById('accept');
const declineRequest = document.getElementById('decline');
const actionsRequest = document.getElementsByClassName('action')
acceptRequest.addEventListener('click', () => {
actionsRequest.style.display = 'none';
this.value = 'X accepted your request';
})
<div class="request">
<div class="info">
<div class="profile-photo">
<img src="Content/request1.jpg" alt="" />
</div>
<div>
<h5>Hajia Bintu</h5>
<p class="text-muted">8 mutual friends</p>
</div>
</div>
<div class="action">
<button class="btn btn-primary" id="accept">Accept</button>
<button class="btn" id="decline">Decline</button>
</div>
</div>
let accept = document.getElementById("accept");
let decline = document.getElementById("decline");
let name = document.getElementById("friend").innerHTML;
accept.onclick = () => {
accept.innerHTML = "You accept " + name + " friend request";
decline.innerHTML = "Decline";
}
decline.onclick = () => {
decline.innerHTML = "You decline " + name + " friend request";
accept.innerHTML = "Accept";
}
<div class="request">
<div class="info">
<div class="profile-photo">
<img src="Content/request1.jpg" alt="" />
</div>
<div>
<h5 id="friend">Hajia Bintu</h5>
<p class="text-muted">8 mutual friends</p>
</div>
</div>
<div class="action">
<button class="btn btn-primary" id="accept">Accept</button>
<button class="btn" id="decline">Decline</button>
</div>
</div>
const acceptRequest = document.getElementById('accept');
const declineRequest = document.getElementById('decline');
const actionsRequest = document.getElementsByClassName('action')[0]
acceptRequest.addEventListener('click', () => {
actionsRequest.style.display = 'none';
this.value = 'X accepted your request';
})
<div class="request">
<div class="info">
<div class="profile-photo">
<img src="Content/request1.jpg" alt="" />
</div>
<div>
<h5>Hajia Bintu</h5>
<p class="text-muted">8 mutual friends</p>
</div>
</div>
<div class="action">
<button class="btn btn-primary" id="accept">Accept</button>
<button class="btn" id="decline">Decline</button>
</div>
</div>

Trying to loop through click event and make the div´s with it´s texts visible. Does somebody what the mistake is?

Here is the html container:
<div class="arrow-1">
<div class="text-event">
<p class="text-style-11">Text 1
</p>
</div>
<div class="arrow">
<div class="diamond">
</div>
</div>
</div>
<div class="arrow-2">
<div class="text-event">
<p class="text-style-11">Text 2
</p>
</div>
<div class="arrow">
<div class="diamond">
</div>
</div>
</div>
<div class="arrow-3">
<div class="text-event">
<p class="text-style-11">Text 3
</p>
</div>
<div class="arrow">
<div class="diamond">
</div>
</div>
</div>
<div class="arrow-4">
<div class="text-event">
<p class="text-style-11"> Text 4
</p>
</div>
<div class="arrow">
<div class="diamond">
</div>
</div>
</div>
<div class="arrow-5">
<div class="text-event">
<p class="text-style-11"> Text 5
</p>
</div>
<div class="arrow">
<div class="diamond">
</div>
</div>
</div>
</div>
The paragraphs should be "visible" when text-event class clicked. Text style class is "hidden" by default. I did that already with other div boxes and it worked. Is there a 'p' declaration missing in the loop function? There is not even a console feedback when I pass the textEvent variable to the console.
const textEvent = document.querySelectorAll('.text-event');
for (var j = 0; j < textEvent.length; j++) (function (j) {
textEvent[j].addEventListener('click', onclick);
textEvent[j].onclick = function (ctrls) {
ctrls.forEach(ctrl => {
/* ctrl.getElementsByClassName('p')[0].innerHTML; */
ctrl.document.getElementsByClassName('text-style-11').style.visibility = "visible";
})
}
})(j);
I could not understand very well your code but this is how I would do it.
First get all the element with class "text-event"
loop over that array and add an event listener to each of them.
When you click in one of them select the element with the class of text-style-11
To something to that element.
const textContainers = document.querySelectorAll(".text-event");
textContainers.forEach((element) => {
element.addEventListener("click", () => {
const textElement = element.querySelector(".text-style-11");
textElement.style.visibility = "hidden";
});
});
Instead of adding styles directly, I recommend you to create a class and use classList toggle to add and remove that class.
textContainers.forEach((element) => {
element.addEventListener("click", () => {
const textElement = element.querySelector(".text-style-11");
textElement.classList.toggle("show");
});
});
I have tested this code it should work fine:
const textEvent = document.querySelectorAll('.text-event');
for (var j = 0; j < textEvent.length; j++) {
textEvent[j].addEventListener('click', (el) => {
const clickedElement = el.currentTarget;
const innerParagraph = clickedElement.querySelector('.text-style-11');
innerParagraph.style.visibility = 'visible';
});
}
You've already got a valid answer.. by the way here's the live snippet using the proper strategy to add an event listener to all your .text-event elements that will hide the inner paragraph embedded in the clicked box:
document.querySelectorAll('.text-event').forEach((el) => {
el.addEventListener('click', (event) => {
const clickedElement = event.currentTarget;
const innerParagraph = clickedElement.querySelector('.text-style-11');
innerParagraph.style.visibility = 'visible';
});
});
.text-event {
border: dotted gray 3px;
margin-bottom: 2px;
cursor: pointer;
}
.text-style-11{
visibility: hidden;
}
<div class="arrow-1">
<div class="text-event">
<p class="text-style-11">Alle Personen, die nicht sozialversicherungspflichtig beschäftigt sind (Beamte, Selbstständige, etc.)
</p>
</div>
<div class="arrow">
<div class="diamond">
</div>
</div>
</div>
<div class="arrow-2">
<div class="text-event">
<p class="text-style-11">Einmalige Wartezeit 1 Monate
</p>
</div>
<div class="arrow">
<div class="diamond">
</div>
</div>
</div>
<div class="arrow-3">
<div class="text-event">
<p class="text-style-11">Keine Karenzzeit
</p>
</div>
<div class="arrow">
<div class="diamond">
</div>
</div>
</div>
<div class="arrow-4">
<div class="text-event">
<p class="text-style-11">Versichert sind nur Erstdiagnosen während der Versicherungslaufzeit (Herzinfarkt, Schlaganfall, Krebs, Blindheit oder Taubheit)
</p>
</div>
<div class="arrow">
<div class="diamond">
</div>
</div>
</div>
<div class="arrow-5">
<div class="text-event">
<p class="text-style-11">Übernahme des noch ausstehenden Restsaldos von bis zu 135.000 €
</p>
</div>
<div class="arrow">
<div class="diamond">
</div>
</div>
</div>

if else condition is not working in foreach

I am using if else in a foreach loop and binding that value with the container but I don't understand Why if else condition is not working in foreach it is showing if else statement in html page like if({detailInfo.condition} !== ""){} but condition is not working? how can I use if else in a div element?
async function renderViewDetails(data, dataTableOrders) {
let ordersDetails = data.group_id;
var detailInfos = dataTableOrders;
let html =
`<div class="viewDetailModal">
<div class="detailButtonModal">
<p class="viewOrderId">ID:</p>
<p class="orderdetailsid viewOrderId">${data.id}</p>
<p class="coinviewDetail">${data.coin}</p>
</div>
<div class="rb-container">
<ul class="rb">`;
detailInfos.forEach(detailInfo => {
if (detailInfo.group_id == ordersDetails) {
let htmlSegment = `
<li class="rb-item timelimeVertical" ng-repeat="itembx">
<div class="tradingOrdersInfo">
<p class="orderDetailDate">${detailInfo.openedAt}</p>
<div class="tradeOrderType">
<p class="viewDetailOrderType">${detailInfo.type}</p>
<button id="showMoreLess_${detailInfo.id}"
data-order-id="${detailInfo.id}"
class="viewDetailOrderButton">View
More</button>
</div>
<div id="showme_${detailInfo.id}" style="display:none";>
<div class="tradeOrderEntry">
<div>
<p class="orderDetailQuantity">Quantity:</p>
<p class="orderDetailQuantityValue">${detailInfo.volume}</p>
</div>
<div class="tradeOrdervaluePrice">
<p class="orderPnlInner"> ${detailInfo.group_pnl}</p>
<p class="pnlInnerLabel">PNL</p>
</div>
</div>
<div class="tradeOrderEntry tradeOrderEntryValue">
<div>
<p class="detailEntryValue entryOpa ">TP Target</p>
<p class="detailEntryValue entryOpa">Entry Target</p>
</div>
if({detailInfo.condition} !== null){
<div>
<p class="detailEntryValueR viewPadd">{detailInfo.condition}</p>
<p class="detailEntryValueR"> {detailInfo.condition} </p>
</div>
</div>
}
<div class="tradeOrderEntry tradeOrderEntryValue">
<div>
<p class="detailEntryValue entryOpa">Expire</p>
</div>
</div>
</div>
</li>`
html += htmlSegment;
}
});
html += `</ul></div></div>`;
let container = document.querySelector('.orders-details-info');
container.innerHTML = html;
}

How to bind this within js nested object iteration within a function. Jquery

again, probably a terrible title - but what I'm trying to do is to make a simple search feature on my website. You click a nav button, which updates the search bar, whi in turn triggers an onchange event to update the current appended list.
function update() {
var list = $("#comic__modern-list");
list.empty();
$.each(Object.keys(comics), function() {
var currentObject = comics[this];
var filter = comics[this].type;
var publisher = comics[this].publisher;
if (search == "") {
if(filter == "modern") {
list.append(`
<div class="comic__box">
<div class="comic__image-box">
<img src="${currentObject['data-item-image']}" alt="${currentObject['data-item-description']}" class="img-fluid">
<div class="comic__desc-wrap">
<div class="comic__desc">${currentObject['data-item-description']}, issue #${currentObject['issue']} (${currentObject['year']})</div>
</div>
</div>
<div style="text-align:center; margin-top: 1rem">
<button
class="btn btn-warning snipcart-add-item comic__button"
data-item-id="${currentObject['data-item-id']}"
data-item-price="${currentObject['data-item-price']}"
data-item-url="${currentObject['data-item-url']}"
data-item-description="${currentObject['data-item-description']}"
data-item-image="${currentObject['data-item-image']}"
data-item-name="${currentObject['data-item-name']}">
<div class="comic__desc-desk">£${currentObject['data-item-price']}<br>Add to cart</div><div class="comic__desc-mob">BUY <br> ${currentObject['data-item-description']}, Issue: ${currentObject['issue']} (${currentObject['year']})</div>
</button>
</div>
</div>
`)
}
} else if (search == publisher) {
list.append(`
<div class="comic__box">
<div class="comic__image-box">
<img src="${currentObject['data-item-image']}" alt="${currentObject['data-item-description']}" class="img-fluid">
<div class="comic__desc-wrap">
<div class="comic__desc">${currentObject['data-item-description']}, issue #${currentObject['issue']} (${currentObject['year']})</div>
</div>
</div>
<div style="text-align:center; margin-top: 1rem">
<button
class="btn btn-warning snipcart-add-item comic__button"
data-item-id="${currentObject['data-item-id']}"
data-item-price="${currentObject['data-item-price']}"
data-item-url="${currentObject['data-item-url']}"
data-item-description="${currentObject['data-item-description']}"
data-item-image="${currentObject['data-item-image']}"
data-item-name="${currentObject['data-item-name']}">
<div class="comic__desc-desk">£${currentObject['data-item-price']}<br>Add to cart</div><div class="comic__desc-mob">BUY <br> ${currentObject['data-item-description']}, Issue: ${currentObject['issue']} (${currentObject['year']})</div>
</button>
</div>
</div>
`)
}
});
}
The current list is generated by this, which works fine:
$.each(Object.keys(comics), function() {
var currentObject = comics[this];
var currentObject2 = comics[this].type;
console.log(currentObject2);
if (search == "") {
if(currentObject2 == "modern") {
var list = $("#comic__modern-list");
list.append(`
<div class="comic__box">
<div class="comic__image-box">
<img src="${currentObject['data-item-image']}" alt="${currentObject['data-item-description']}" class="img-fluid">
<div class="comic__desc-wrap">
<div class="comic__desc">${currentObject['data-item-description']}, issue #${currentObject['issue']} (${currentObject['year']})</div>
</div>
</div>
<div style="text-align:center; margin-top: 1rem">
<button
class="btn btn-warning snipcart-add-item comic__button"
data-item-id="${currentObject['data-item-id']}"
data-item-price="${currentObject['data-item-price']}"
data-item-url="${currentObject['data-item-url']}"
data-item-description="${currentObject['data-item-description']}"
data-item-image="${currentObject['data-item-image']}"
data-item-name="${currentObject['data-item-name']}">
<div class="comic__desc-desk">£${currentObject['data-item-price']}<br>Add to cart</div><div class="comic__desc-mob">BUY <br> ${currentObject['data-item-description']}, Issue: ${currentObject['issue']} (${currentObject['year']})</div>
</button>
</div>
</div>
`)
}
}
});
From what I can gather, this has to do with the keyword "this" no longer meaning what it did when it was outside of the function, so I'm assuming the fix will be to do with bind(), but I can't make heads nor tails of it.
p.s, if there's an easier/simpler way to set up a search system, please enlighten me!

Filter divs by class

I am trying to create a function that returns an additional display of none when you click on a button. It basically filters divs with class names when you click a button. I used a while/do loop to go through all the elements by class name.
In the browser console log it is telling me
"Cannot read property 'style' of undefined".
Does anybody knows what might be the problem?
<div class="container">
<h1 id="title">World's Top suppply chains</h1>
<div class="options">
<button id="allbtn">All</button>
<button>Drinks</button>
<button>Clothing</button>
<button>Cars</button>
<button id="fast-food-btn">Fast Food</button>
</div>
<div class="stores">
<div class="store">
<img src="images/adidas.png">
<h3>Adidas</h3>
<p class="industry">Clothing</p>
</div>
<div class="store">
<img src="images/corona.png">
<h3>Corona</h3>
<p class="industry">Drinks</p>
</div>
<div class="store">
<img src="images/nike.jpg">
<h3>Nike</h3>
<p class="industry">Clothing</p>
</div>
<div class="store">
<img src="images/lambo.png">
<h3>Lamborghini</h3>
<p class="industry">Cars</p>
</div>
<div class="store">
<img src="images/smirnoff.png">
<h3>Smirnoff</h3>
<p class="industry">Drinks</p>
</div>
<div class="store">
<img src="images/pepsi.jpg">
<h3>Pepsi</h3>
<p class="industry">Drinks</p>
</div>
<div class="store">
<img src="images/gucci.png">
<h3>Gucci</h3>
<p class="industry">Clothing</p>
</div>
<div class="store">
<img src="images/heineken.jpg">
<h3>Heineken</h3>
<p class="industry">Drinks</p>
</div>
<div class="store">
<img src="images/lacoste.png">
<h3>Lacoste</h3>
<p class="industry">Clothing</p>
</div>
<div class="store">
<img src="images/ferrari.png">
<h3>Ferrari</h3>
<p class="industry">Cars</p>
</div>
<div class="store">
<img src="images/pizzahut.png">
<h3>Pizza Hut</h3>
<p class="industry">Fast Food</p>
</div>
<div class="store">
<img src="images/cocacola.png">
<h3>Coca Cola</h3>
<p class="industry">Drinks</p>
</div>
<div class="store">
<img src="images/mc.png">
<h3>Mc Donalds</h3>
<p class="industry">Fast Food</p>
</div>
</div>
</div>
<script>
const industry = document.getElementsByClassName(".industry");
const fastFood = document.getElementById("fast-food-btn");
allbtn.addEventListener("click", filter);
function filter(){
const card = industry.parentElement;
do{
card.style.display = "none";
}
while(industry.innerHTML === "Fast Food");
}
</script>
First issue is that you don't need the dot in front of the class when using getElementsByClassName.
Secondly getElementsByClassName returns a HTMLCollection which does not have a property called parent.
Which results in something like this:
function filter() {
const industries = document.getElementsByClassName("industry");
for (let industry of industries) {
industry.style.display = "none";
}
}
Furthermore, it looks like the variable fastFood is not used and the variable allbtn is undefined. I assume it shoul be something like this:
const allbtn = document.getElementById("allbtn");
Putting it together, this should solve your problem:
<script>
function filter() {
const industries = document.getElementsByClassName("industry");
for (let industry of industries) {
industry.style.display = "none";
}
}
const allbtn = document.getElementById("allbtn");
allbtn.addEventListener("click", filter);
</script>

Categories

Resources