Add Button for Selected Product Cards using JavaScript - javascript

I am working with e-commerce site. How do I add a button exclusively to product cards that contain audio file?
var products = document.querySelectorAll('ul.products');
products.forEach(function(product){
var voice = product.querySelectorAll('li.product > div.nv-card-content-wrapper');
voice.forEach(function(item) {
var btn = document.createElement('button');
btn.className = 'play_audio';
btn.textContent = "CLICK TO LISTEN";
btn.setAttribute("type", "button");
btn.addEventListener('click', () => {
item.getElementsByTagName('audio')[0].play();
})
if (!item.getElementsByTagName('audio')){
btn.style.visibility = "hidden";
}
item.appendChild(btn);
});
})
This is the sample page: https://staging.buellairhorns.com/product-category/horns/page/2

Just got it solved. I just need to change my condition from
!item.getElementsByTagName('audio')
to
!item.getElementsByTagName('audio')[0]

Related

How to implement dynamic buttons html using insertAdjacentHTML JS Method?

I'm creating a Chrome extension to download videos from a certain site, I need to show the available resolutions buttons in an insertAdjacentHTML, but I don't know how to implement it.
my code:
const list = ['240p', '480p', '720p', '1080p']
const container = document.querySelector('.video-info-container');
container.insertAdjacentHTML('beforebegin',`
<ul class="mlext-container">
<li>AVALIABLE RESOLUTIONS: <span> <div id="container"></div> </span></li>
</ul>`)
In this case, the buttons should be added to the <div id="container"></div> from the code above
I have this code above that creates the buttons in the index.html file inside the body tag if <div id="container"></div> is there,but I want to create them inside the code that was inserted by the insertAjacentHTML method
list.forEach(element => {
document.addEventListener('DOMContentLoaded', function () {
var button = document.createElement('button');
button.type = 'button';
button.innerHTML = element;
button.className = 'btn-styled';
button.id = element
button.onclick = function () {
if (button.id == '240p') {
var linkRequest =
console.log(element)
}
if (button.id == '480p') {
console.log(element)
}
if (button.id == '720p') {
console.log(element)
}
if (button.id == '1080p') {
console.log(element)
}
};
var container = document.getElementById('container');
container.appendChild(button);
}, false);
});
how to do it?

Attach the Complete button to new tasks in a to do list app

I tried to build a to do list app. My code doesn't attach the Complete button to the new tasks.
edit: After changing the code, I realized I'd like to store it in the LocalStorage, but I can't figure out a way how.
var addBtn = document.getElementById("addButton");
var textInput = document.getElementById("textInput");
var mainList = document.getElementById("mainList");
function addCompleteBtn (newTask){
let completeBtn = document.createElement("button");
completeBtn.className="btn btn-success";
completeBtn.id="completeBtn"
completeBtn.textContent="Completed";
newTask.appendChild(completeBtn);
};
addBtn.addEventListener("click", ()=>{
var newTask = document.createElement("li");
if(textInput.value === ""){
alert("Please enter a task");
}else{
newTask.textContent=textInput.value
newTask.className="task d-flex justify-content-between list-group-item bg-primary mt-2";
addCompleteBtn(newTask);
mainList.appendChild(newTask);
textInput.value="";
}
});
mainList.addEventListener("click",(evt)=>{
if (evt.target.id==="completeBtn") {
let listItem = evt.target.parentNode
let mainUl = listItem.parentNode
mainUl.removeChild(listItem);
}
});
You want document.createElement not createItem

Why does this javascript function activate at the wrong time?

Here's the code I'm currently using
function firstChildAge() {
var header = document.createElement('H3');
var body = document.getElementsByTagName('BODY');
var textnode = document.createTextNode("WHAT IS THE AGE OF THE FIRST CHILD?");
var inputChildOne = document.createElement("Input");
var childOneAgeResponse = inputChildOne.value;
header.appendChild(textnode);
document.body.appendChild(header);
document.body.appendChild(inputChildOne);
}
function submitButton() {
var btn = document.createElement('Button');
document.body.appendChild(btn);
btn.onClick = testFunction_2();
}
function testFunction_2() {
alert("foo");
}
if (childrenResponse == 1) {
firstChildAge();
submitButton();
}
As you can see, if childrenResponse (the user's response to a previous query) is equal to 1, both functions are activated. The attempted goal is to create a text node, an input, and a button. The button as of right now, should active testFunction2() which alerts us that it is working. But, testFunction2() activates before the text node or input even shows up. I can find the reason for this, and if anyone can help me out I'd greatly appreciate it. Thank you.
Also, on a side note, how can I add text to the button created in submitButton() ? Thanks!
You have called the testFunction_2, instead of assigning it. This should work out fine.
function submitButton() {
var btn = document.createElement('Button');
btn.onclick = testFunction_2;
document.body.appendChild(btn);
}
You are calling the function testFunction_2() in onClick. You need to add event listener to button as shown below
btn.addEventListener('click', testFunction_2);
To add text to button use
var txt = document.createTextNode("CLICK ME");
btn.appendChild(txt);
Check the snippet below
function firstChildAge() {
var header = document.createElement('H3');
var body = document.getElementsByTagName('BODY');
var textnode = document.createTextNode("WHAT IS THE AGE OF THE FIRST CHILD?");
var inputChildOne = document.createElement("Input");
var childOneAgeResponse = inputChildOne.value;
header.appendChild(textnode);
document.body.appendChild(header);
document.body.appendChild(inputChildOne);
}
function submitButton() {
var btn = document.createElement('Button');
var txt = document.createTextNode("CLICK ME");
btn.appendChild(txt);
document.body.appendChild(btn);
btn.addEventListener('click', testFunction_2);
}
function testFunction_2() {
alert("foo");
}
childrenResponse = 1;
if (childrenResponse == 1) {
firstChildAge();
submitButton();
}
You are calling the function testFunction_2 in onClick. You need to provide reference.
That also won't work. You need to add event listener to button.
And for setting the text, just set innerHTML of button.
var btn = document.createElement('Button');
btn.innerHTML = "click";
btn.addEventListener('click', testFunction_2);
document.body.appendChild(btn);
btn.onclick = testFunction_2; // in place of addEventListener.
// if you want to use onclick. use small case 'c' in onclick.
There were 2 problems:
onClick should've been onclick.
You were executing the function and assigning the result of that function to the onclick. btn.onClick = testFunction_2(); should be btn.onClick = testFunction_2;
See working snippet below.
function firstChildAge() {
var header = document.createElement('H3');
var body = document.getElementsByTagName('BODY');
var textnode = document.createTextNode("WHAT IS THE AGE OF THE FIRST CHILD?");
var inputChildOne = document.createElement("Input");
var childOneAgeResponse = inputChildOne.value;
header.appendChild(textnode);
document.body.appendChild(header);
document.body.appendChild(inputChildOne);
}
function testFunction_2() {
alert("foo");
}
function submitButton() {
var btn = document.createElement('button');
btn.innerHTML = "Some button name";
btn.onclick = testFunction_2;
document.body.appendChild(btn);
}
var childrenResponse = 1;
if (childrenResponse == 1) {
firstChildAge();
submitButton();
}
In javascript you can use the innerHTML set the button's HTML contents.
See Setting button text via javascript
btn.innerHTML = "This is a button name";
The Mozilla Developer Network is a good resource. Here's two links for the above mentioned snippets.
MDN innerHTML
MDN HTML Button element

How to click all buttons of a specific class with one button in javascript

The buttons that i want to click with one button.
The following button are created with every file upload so thats why it is buttons.
var td4=row.insertCell(-1);
td4.innerHTML="<a type='button' class='delete-button' href='javascript:void(0)' onclick='Attachment_Remove(this)'><i class='fa fa-trash' aria-hidden='true'></i> delete</a>";
What i want:
I want to have a button created in js and then when i click that button it should click all buttons of the upper class.
What i have tried:
// 1. Create the button
var button = document.createElement("button");
button.setAttribute("onclick", "divFunction()");
function divFunction(){
var a = document.getElementsByClassName('delete-button');
for(var i = 0; i <= a.length; i++)
a[i].click();
}
// 2. Append somewhere
var body = document.getElementsByTagName("body")[0];
body.appendChild(button);
Here is a simple function that does the job:
const addAButtonThatClicksAllButtons = () => {
const button = document.createElement('button');
button.onclick = () =>
Array.from(document.getElementsByClassName('delete-button'))
.forEach(btn => btn.click());
document.body.appendChild(button);
};
It might be cleaner if you use jQuery:
const addAButtonThatClicksAllButtons = () => {
const button = $('<button/>').click(
() => $('delete-button').click()
);
$('body').append(button);
};

Only update added javascript elements on second click

I have some Javascript code that gets values from an array that processes a http response from a server and adds buttons to a modal window. So the ids for the buttons come from the array.
On second click everything is fine and my buttons are added to the modal window. But when I call the function the next time it adds the buttons again, but it should only update the buttons.
How can I handle it that the function will only update the buttons on second and further clicks?
buttonContainer = document.getElementById('modal1');
for (i = 0; i < resultContainers.length; i++) {
newButton = document.createElement('input');
newButton.type = 'button';
newButton.value = resultContainers[i];
newButton.id = resultContainerValues[i];
newButton.class = 'buttonContainer';
if (newButton.id == 'true') {
newButton.style.backgroundColor = '#8cff1a';
};
newButton.onclick = function () {
alert('You pressed '+this.id);
};
buttonContainer.appendChild(newButton);
You need to check if the button already exists before you add it in that case. Since you know the id of the button you're about to create, you can see if there's already a button with that id and just update it instead.
var newButton = document.getElementById(resultContainerValues[i]);
if(newButton!=null) {
newButton.value = resultContainers[i];
} else {
newButton = document.createElement('input');
newButton.type = 'button';
newButton.value = resultContainers[i];
newButton.id = resultContainerValues[i];
newButton.class = 'buttonContainer';
if (newButton.id == 'true') {
newButton.style.backgroundColor = '#8cff1a';
}
newButton.onclick = function () {
alert('You pressed '+this.id);
};
buttonContainer.appendChild(newButton);
}

Categories

Resources