How to I replace these two buttons with a text in Javascript - 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>

Related

I am getting an errror while clicking the button of producing sound

Whenever I want to play the sound of the
word it doesn't play that sound and gives me an error of "The element has no supported sources".
Have a look into this please and let me know where I'm doing something wrong.
Html
<audio id="micCheck"></audio>
<div id="container">
<div id="box-1">
<input
type="text"
placeholder="Type your word here.."
id="searchWord"
/>
<button id="btn">Search</button>
</div>
<div class="output" id="output"></div>
</div>
<script src="script.js"></script>
Javascript
const searchButton = document.getElementById("btn");
const searchField = document.getElementById("searchWord");
const volume = document.getElementById("micCheck");
const url = "https://api.dictionaryapi.dev/api/v2/entries/en/";
searchButton.addEventListener("click", () => {
let saveWord = searchField.value;
fetch(`${url}${saveWord}`)
.then((response) => response.json())
.then((values) => {
console.log(values);
output.innerHTML = `
<div id="box-2">
<h3>${values[0].word}</h3>
<button onclick="playSound()">
<i class="fas fa-volume-up">
</i>
</button>
</div>
<div id="box-3">
<p>${values[0].meanings[0].partOfSpeech}</p>
<p> ${values[0].phonetic} </p>
</div>
<div id="box-4">
<p>
${values[0].meanings[0].definitions[0].definition}</br>
</p>
<p id="paragraph-2">
${values[0].meanings[0].definitions[0].example || ""}
</p>`;
volume.setAttribute("src", `https:${values[0].phonetics[0].audio}`);
});
});
function playSound() {
volume.play();
}

how to add an Enter key event listener?

btnSend.addEventListener('click', async(event)=>{
event.preventDefault()
let userInput = txtInput.value;
let temp = `<div class="out-msg">
<span class="my-msg">${userInput}</span>
<img src="static/img/me.jpeg" class="picture">
</div>`;
chatWindow.insertAdjacentHTML("beforeend", temp);
txtInput.value = ''
scrollSmoothlyToBottom()
txtInput.value = '';
const botResponse = await chatBotChat(userInput)
let tempBot = `<div class="out-msgbot">
<img src="static/img/bot.jpeg" class="picture">
<span class="my-msg">${botResponse}</span>
</div>`;
chatWindow.insertAdjacentHTML("beforeend", tempBot);
scrollSmoothlyToBottom()
})
this is from my .html file
<form class="popup-chat" action="">
<div class="title">Virtual Assitant</div>
<div class="badge">!</div>
<div class="chat-window" id="chat-window">
<div class="bot-msg">
<img src="{{ url_for('static', filename='img/bot.jpeg')}}" alt="" class="picture">
<span class="msg">Hi, How can i help you?</span>
</div>
<p id="scrollv"></p>
</div>
<div class="input-area" id="input-area">
<input autocomplete="off" type="text" name="msg" id="txtInput"/>
<button id="btn-emoji">🌝</button>
<button class="btn-send"> <i class="material-icons">send</i></button>
</div>
</form>
How should i add an enter key listerner to this code?
I could only send a message by clicking on the submit button. Thanks for the help. im a beginner.
Hope this helps to you.
document.onkeydown = (event) => {
if (event.key === "Enter") {
//Add your Enter event code here, like this.
alert('Hi, Insert what you want to run here');
}
}

Can't delete div's with new added buttons

after I keep creating new DIVs with my javascript functions, the new ones don't delete themselves.
My codes creates a post it div which gives info about title, author, and pages, and a X button that when you press it, it deletes it.
It works for my first 4 HTML examples, but not with the newly added divs from javascript.
const container = document.querySelector('.right');
let removeButtons = document.querySelectorAll('.remove');
let removeButtonsArray = Array.prototype.slice.call(removeButtons);
let bookNum = 4;
function addBook() {
const titleAdd = document.getElementById('title-add').value;
const readAdd = document.getElementById('read-add').value;
const totalAdd = document.getElementById('total-add').value;
if (titleAdd == '' || readAdd == '' || totalAdd == '') {
alert('Complete all of the boxes');
return;
} else if (readAdd > totalAdd) {
alert('why are you lying? =[[');
return;
}
const book = document.createElement('div');
book.classList.add('book');
container.appendChild(book);
const xButton = document.createElement('button');
xButton.classList.add('remove');
book.appendChild(xButton);
xButton.innerHTML = 'X';
const title = document.createElement('h2');
book.appendChild(title);
title.innerHTML = titleAdd;
const author = document.createElement('h3');
book.appendChild(author);
author.innerHTML = document.getElementById('author-add').value;
const pages = document.createElement('h3');
book.appendChild(pages);
const pagesNumber = readAdd + '/' + totalAdd;
pages.classList.add('page-num')
pages.innerHTML = pagesNumber;
bookNum++;
removeButtons = document.querySelectorAll('.remove');
removeButtonsArray = Array.prototype.slice.call(removeButtons);
}
const button = document.querySelector('.add');
button.onclick = addBook;
removeButtonsArray.forEach(removeButton => removeButton.addEventListener('click', function() {
const remove = removeButtonsArray.indexOf(removeButton);
removeButtonsArray.splice(remove, 1);
document.querySelector('.book').remove();
bookNum--;
}));
<div class="container">
<div class="left">
<div class="title-add">
<h2>Title:</h2>
<input type="text" id="title-add" name="title-add" max="30">
</div>
<div class="author-add">
<h2>Author:</h2>
<input type="text" id="author-add" name="author-add" max="30">
</div>
<div class="pages">
<div class="pages-read">
<h3>Pages read:</h3>
<input type="number" id="read-add" min="0" name="read">
</div>
<div class="pages-total">
<h3>Total pages:</h3>
<input type="number" id="total-add" min="1" name="total">
</div>
</div>
<button class="add">Add book</button>
</div>
<div class="right">
<div class="book">
<button class="remove">X</button>
<h2 class="title">muie</h2 >
<h3 class="author">Csokmai Robert123</h3>
<h3 class="page-num">31/316</h3>
</div>
<div class="book">
<button class="remove">X</button>
<h2>muie</h2 >
<h3>Csokmai Robert</h3>
<h3 class="page-num">31/316</h3>
</div>
<div class="book">
<button class="remove">X</button>
<h2>muie</h2 >
<h3>Csokmai Robert</h3>
<h3 class="page-num">31/316</h3>
</div>
<div class="book">
<button class="remove">X</button>
<h2>muie</h2 >
<h3>Csokmai Robert</h3>
<h3 class="page-num">31/316</h3>
</div>
</div>
</div>
I tried everything but I just don't know how to fix it
Problems:
There are a few Problems with your code:
Delete function doesn't actually work, because every time you are just removing the first element which has book class. document.querySelector('.book').remove();
The reason the Delete button for Dynamically added books was not working is because this bit of code removeButtonsArray.forEach(removeButton => removeButton.addEventListener was executed only on first execution. So, newly added buttons weren't getting the Event Listener registered for them.
Solutions:
Delete functionality can be easily handled by targeting the parentElement of the Delete Button which was clicked.
For the Dynamically added Books' Delete Functionality, We need to register the click Event Listener for each one of them during creation.
const container = document.querySelector('.right');
let removeButtons = document.querySelectorAll('.remove');
let bookNum = 4;
function addBook() {
const titleAdd = document.getElementById('title-add').value;
const readAdd = document.getElementById('read-add').value;
const totalAdd = document.getElementById('total-add').value;
if (titleAdd == '' || readAdd == '' || totalAdd == '') {
alert('Complete all of the boxes');
return;
} else if (readAdd > totalAdd) {
alert('why are you lying? =[[');
return;
}
const book = document.createElement('div');
book.classList.add('book');
container.appendChild(book);
const xButton = document.createElement('button');
xButton.classList.add('remove');
book.appendChild(xButton);
xButton.innerHTML = 'X';
const title = document.createElement('h2');
book.appendChild(title);
title.innerHTML = titleAdd;
const author = document.createElement('h3');
book.appendChild(author);
author.innerHTML = document.getElementById('author-add').value;
const pages = document.createElement('h3');
book.appendChild(pages);
const pagesNumber = readAdd + '/' + totalAdd;
pages.classList.add('page-num')
pages.innerHTML = pagesNumber;
bookNum++;
// Adding Click Event to new Books Delete Button
xButton.addEventListener("click", removeBook);
}
const button = document.querySelector('.add');
button.onclick = addBook;
// Function for Removing Book
function removeBook(e) {
// Since we are getting the Delete Buttons event as Frunction Argument
// We can get access to it's parentElement i.e., the target Book Div
e.target.parentElement.remove();
bookNum--;
}
removeButtons.forEach(removeButton => removeButton.addEventListener('click', removeBook));
<div class="container">
<div class="left">
<div class="title-add">
<h2>Title:</h2>
<input type="text" id="title-add" name="title-add" max="30">
</div>
<div class="author-add">
<h2>Author:</h2>
<input type="text" id="author-add" name="author-add" max="30">
</div>
<div class="pages">
<div class="pages-read">
<h3>Pages read:</h3>
<input type="number" id="read-add" min="0" name="read">
</div>
<div class="pages-total">
<h3>Total pages:</h3>
<input type="number" id="total-add" min="1" name="total">
</div>
</div>
<button class="add">Add book</button>
</div>
<div class="right">
<div class="book">
<button class="remove">X</button>
<h2 class="title">muie</h2>
<h3 class="author">Csokmai Robert123</h3>
<h3 class="page-num">31/316</h3>
</div>
<div class="book">
<button class="remove">X</button>
<h2>muie</h2>
<h3>Csokmai Robert</h3>
<h3 class="page-num">31/317</h3>
</div>
<div class="book">
<button class="remove">X</button>
<h2>muie</h2>
<h3>Csokmai Robert</h3>
<h3 class="page-num">31/315</h3>
</div>
<div class="book">
<button class="remove">X</button>
<h2>muie</h2>
<h3>Csokmai Robert</h3>
<h3 class="page-num">31/314</h3>
</div>
</div>
</div>

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!

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

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>

Categories

Resources