Link View Product button to that page using JavaScript - javascript

I want to link the view button to their represented page.
The image shown is the product page.
When the user clicks on the view product it should send them to that product page.
The led plastic tube light for example should be send to that product page.
JS code for it:
{
productName: "LED Plactice Tube Light",
category: "LEDLightsIndoor",
image: "/img/glass-plastic-tubelight.jpg",
info:"Available in Warm, Pure & Natural White.",
info2:"Used in offices, retail stores, boardrooms, hotels, homes, banks, restaurants
and many more.",
info3:"Saves up to 90% electricity.",
button: "View Product",
},
To display the data:
for (let i of products.data) {
//Create Card
let card = document.createElement("div");
//Card should have category and should stay hidden initially
card.classList.add("card", i.category, "hide");
//image div
let imgContainer = document.createElement("div");
imgContainer.classList.add("image-container");
//img tag
let image = document.createElement("img");
image.setAttribute("src", i.image);
imgContainer.appendChild(image);
card.appendChild(imgContainer);
//container
let container = document.createElement("div");
container.classList.add("container");
//product name
let name = document.createElement("h5");
name.classList.add("product-name");
name.innerText = i.productName.toUpperCase();
container.appendChild(name);
//info
let info = document.createElement("div");
info.classList.add("info");
info.innerText = i.info.toUpperCase();
container.appendChild(info);
let info2 = document.createElement("div");
info2.classList.add("info");
info2.innerText = i.info2.toUpperCase();
container.appendChild(info2);
let info3 = document.createElement("div");
info3.classList.add("info");
info3.innerText = i.info3.toUpperCase();
container.appendChild(info3);
//view product button
let button = document.createElement("div");
button.classList.add("glow-on-hover");
button.innerText = i.button.toUpperCase();
container.appendChild(button);
card.appendChild(container);
document.getElementById("products").appendChild(card);
}
How do I create the link for it then?

Related

I want to use vanilla JS to remove the parent element of the button I'm pressing on click

I created a meme generator that accepts text and images and puts them all together. The generator creates a unique ID for each 'meme' and also adds buttons that show up on hover to "delete" the meme. I used vanilla JS to create this and therefore had to layer a few different child divs on top of one another: image, top text, bottom text using z-index.
I am struggling, however, to get the button to delete the parent div. I want to be able to click that delete button, and have the parent div deleted so that the button goes away, along with image and text. picture below + code snippets.
I attemped to do it with vanilla javascript, by adding a closeTheMeme function on click to each button:
let deleteBtns = document.getElementsByClassName('.delete');
function closeTheMeme (){
this.parentElement.parentElement.removeChild();
};
for(let i=0;i<deleteBtns.length;i++){
deleteBtns[i].addEventListener("click",closeTheMeme);
}
No errors on console...Including the rest of the JS below so you can see how the elements are created on click of the meme generator.
'use strict';
let count=0;
// SUBMIT FORM
document.getElementById('memeInput').addEventListener('submit',function(e){
count++;
//prevent default
e.preventDefault();
//set image, top, and bottom to variables we can work with
let bottomText = document.getElementById('bottomText').value;
createMeme();
})
function createMeme(){
//create a meme section with an ID of the number of times the button was clicked, and add it to the meme section
let meme = document.createElement("DIV");
document.body.appendChild(meme);
meme.setAttribute("id", "meme"+count);
//create an image, set that image to equal the link, give it an id based on form submits, set image.src equal to the link
let img = document.createElement("IMG");
img.setAttribute("id","image"+count);
let imageLink = document.getElementById('imageLink').value;
meme.appendChild(img);
document.getElementById("image"+count).src=imageLink;
//set top text variable equal to the ID of toptext. value(form submission)
let topText = document.getElementById('topText').value;
let top = document.createElement('DIV');
top.setAttribute("id","topText"+ count);
meme.appendChild(top);
top.innerHTML = topText;
//set bottom text variable equal to the ID of toptext.value form submission
let bottomText = document.getElementById('bottomText').value;
let bottom = document.createElement('DIV');
bottom.setAttribute("id","bottomText" + count);
meme.appendChild(bottom);
bottom.innerHTML = bottomText;
//add a button that deletes the meme in the same way as above
let deleteButton = document.createElement("BUTTON");
deleteButton.classList.add("delete");
deleteButton.innerHTML = "Delete";
meme.appendChild(deleteButton);
//styling and position
meme.classList.add("meme");
top.classList.add("topWords");
bottom.classList.add("bottomWords");
};
let deleteBtns = document.getElementsByClassName('.delete');
function closeTheMeme (){
this.parentElement.parentElement.removeChild();
};
for(let i=0;i<deleteBtns.length;i++){
deleteBtns[i].addEventListener("click",closeTheMeme);
}
You select the buttons when the page loads. You created no buttons so it is not possible for it to work since there is nothing to bind an event to.
Since you are making the buttons, add the event there.
const deleteButton = document.createElement("BUTTON");
deleteButton.addEventListener("click", function () {
this.closest("div").remove();
});
Other option is event delegation
document.body.addEventListener("click", function (e) {
const btn = e.target.closest(".delete");
if (btn) btn.closest("div").remove();
});

How to show "cart is empty" after all items have been removed using Javascript?

I am a bit stuck and hoping someone can help me, please.
Basically I have coded a shopping cart and am currently trying to get the cart to display a message saying "Cart is empty" after all of the cart items have been removed.
Everything is working ok apart from the "Cart is empty" message being re-displayed after the cart is empty.
I have tried a few things but cannot seem to get the emptyCartMessage to display when removing the last cart item.
Just for extra context my cart items each have an independent 'remove' button attached to them.
My code is below.
Thank you for any help, I do appreciate it!
const currentCartItems = document.getElementsByClassName('cart-item');
const emptyCartMessage = document.createElement('p');
emptyCartMessage.innerHTML = 'Your cart is empty.';
// EMPTY CART ITEM DISPLAY MESSAGE
shoppingCart.appendChild(emptyCartMessage);
// SHOPPING AREA BUTTON EVENT LISTENER
for (var i = 0; i < addToCartButton.length; i++) {
addToCartButton[i].addEventListener('click', createCartItem);
}
function createCartItem(event) {
//CREATE CART LI ITEM
const newItem = document.createElement('li');
newItem.className = 'cart-item';
//newItem.innerHTML = event.target.value;
//GET AND SET SHOP/CART ITEM VALUE
const itemValue = document.createElement('p');
itemValue.innerHTML = event.target.value;
//CREATE CART ITEM DESCRIPTION
const p = document.createElement('p');
p.innerHTML = itemDescription;
//CREATE CANCEL CART ITEM BUTTON
const cancelItemImage = document.createElement('img');
cancelItemImage.className = "remove-button";
cancelItemImage.src = "images/cancel-icon.png";
cancelItemImage.alt = "red remove icon";
newItem.appendChild(itemValue);
newItem.appendChild(p);
newItem.appendChild(cancelItemImage);
shoppingCart.appendChild(newItem);
if (currentCartItems.length > 0) {
emptyCartMessage.className = 'hide-empty-cart';
} else if (currentCartItems.length <= 0) {
emptyCartMessage.classList.remove('hide-empty-cart');
}
}
// REMOVE CART ITEMS BUTTON
shoppingCart.addEventListener('click', (e) => {
if (e.target.className === 'remove-button'){
const li = e.target.parentNode;
const ol = li.parentNode;
ol.removeChild(li);
}
});
Please remove this line
const currentCartItems = document.getElementsByClassName('cart-item');
We will use this variable inside the function 'createCartItem' and inside 'removeCartItem' tha i just created.
So when calling createCartItem we can always show the cart items, because this function adds new items, so the cart is not empty.
Inside remove function first we getting the count of current items, then checking if it is less or equal 0 then we hide cart.
So the final version would be.
const emptyCartMessage = document.createElement('p');
emptyCartMessage.innerHTML = 'Your cart is empty.';
// EMPTY CART ITEM DISPLAY MESSAGE
shoppingCart.appendChild(emptyCartMessage);
// SHOPPING AREA BUTTON EVENT LISTENER
for (var i = 0; i < addToCartButton.length; i++) {
addToCartButton[i].addEventListener('click', createCartItem);
}
function createCartItem(event) {
//CREATE CART LI ITEM
const newItem = document.createElement('li');
newItem.className = 'cart-item';
//newItem.innerHTML = event.target.value;
//GET AND SET SHOP/CART ITEM VALUE
const itemValue = document.createElement('p');
itemValue.innerHTML = event.target.value;
//CREATE CART ITEM DESCRIPTION
const p = document.createElement('p');
p.innerHTML = itemDescription;
//CREATE CANCEL CART ITEM BUTTON
const cancelItemImage = document.createElement('img');
cancelItemImage.className = "remove-button";
cancelItemImage.src = "images/cancel-icon.png";
cancelItemImage.alt = "red remove icon";
newItem.appendChild(itemValue);
newItem.appendChild(p);
newItem.appendChild(cancelItemImage);
shoppingCart.appendChild(newItem);
// Always show because after every adding, we know that there is
// at least one item, so we always showing cart
emptyCartMessage.className = 'hide-empty-cart';
}
function removeCartItem(event){
if (event.target.className === 'remove-button'){
const li = e.target.parentNode;
const ol = li.parentNode;
ol.removeChild(li);
// Get cart's current items
const currentCartItems = document.getElementsByClassName('cart-item');
// If cart items less then or equal to 0 then hide
if (currentCartItems.length <= 0) {
emptyCartMessage.classList.remove('hide-empty-cart');
}
}
}
// REMOVE CART ITEMS BUTTON
shoppingCart.addEventListener('click', removeCartItem);

How to access elements that were created in script?

In the function below, I create cards that have a toggle button and remove button. However, when I try to access the buttons with a queryselector, I get null. Anyone know how to access elements that were created in a different file? I can provide the full files if needed.
function updateDisplay() {
for (i = 0; i < myLibrary.length; i++){
let div = document.createElement('div');
let title = document.createElement('h5');
let author = document.createElement('h5');
let pages = document.createElement('h5');
let isRead = document.createElement('h5');
let removeButton = document.createElement('button');
let toggleButton = document.createElement('button');
div.classList.add('card');
title.classList.add('title');
author.classList.add('author');
pages.classList.add('pages');
isRead.classList.add('isRead');
removeButton.classList.add('removeButton');
toggleButton.classList.add('toggleButton');
title.textContent = myLibrary[i].title;
author.textContent = myLibrary[i].author;
pages.textContent = `${myLibrary[i].pages} pages`;
isRead.textContent = myLibrary[i].isRead ? 'Read' : 'Unread';
removeButton.textContent = 'Remove';
toggleButton.textContent = 'Toggle Read Status';
Your problem is obvious you're creating the elements but not appending the into the body.
you'll have to append each element you create like the following example:
var element= document.createElement("div"); // Create a <div> element
element.innerHTML = "some content"; // Insert text
document.body.appendChild(element); // Append <div> to <body>
note that you can do document.body.append(div,title,author,pages,isRead,removeButton,toggleButton);
to append them all in one line

how do I get the images in my folder to appear in my javascript index?

I'm trying to make a news page in Javascript where every article is on a card. Every card has a headline, an image and the author's name. The headlines show up fine, but the images are broken and the author names don't show up at all. My code looks like this:
function cardCreator(e) {
const cards = document.querySelector('.cards-container');
function cardCreator(e) {
const card = document.createElement('div');
card.classList.add('card');
const headline = document.createElement('div');
headline.classList.add('headline');
headline.textContent = e.headline;
card.appendChild(headline);
const author = document.createElement('div');
author.classList.add('e.author');
card.appendChild(author);
const container = document.createElement('div');
container.classList.add('img');
author.appendChild(container);
const img = document.createElement('img');
img.src = e
container.appendChild(img);
const span = document.createElement('span');
author.appendChild(span);
span.text = `By ${author}`
cards.appendChild(card);
return card;
}
I thought it was the img src, but if I change out the e the whole page breaks so I'm at a loss. Any help would be appreciated.

How to create HTML tags (with content) on the fly with JavaScript?

I am trying to convert this HTML code to be generated by Javascript on the fly for live data.
<div class="dropdown">
<button class="dropbtn">Dropdown</button>
<div class="dropdown-content">
Link 1
Link 2
Link 3
</div>
</div>
Ive found a few methods like: appendChild, getElementById, innerHTML and so on. Here is what I've tried so far. I can't seem to get the data to show up.
stringy = data2.Items[0].groupName.values[i];
var para = document.createElement("div");
var node = document.createTextNode(stringy);
para.appendChild(node);
var element = document.getElementById("parental");
element.appendChild(para);
//create div and give it a class
para.setAttribute('class', 'dropbtn');
var div = document.createElement("div");
div.setAttribute('class', 'dropdown-content');
para.parentNode.insertBefore(div, para.nextSibling);
//create link tags and give them text
var alinky = document.createElement("a");
alinky.setAttribute('id', 'linky');
document.getElementById('linky').innerHTML = "linky poo"
div.appendChild(alinky);
Hopefully someone could fill in the blanks on getting this HTML code to be reproduced with javascript. Thanks in advance!
EDIT:
I am trying to create a dropdown menu like this:
https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_js_dropdown_hover
However, I am trying to create multiple dropdown menus, that dynamically change in quantity based on a query to DynamoDB (AWS). therefore I am using javascript to create the html tags.
The problem is that the scope of the query function does not allow me to see the data outside of the query function, or even inject data into it.
For example, if I try to get a button description from the query, and write to it descriptionArray[0] = data2.Items[0].description; so that I can append the button to the dropdown div, it doesn't know which iteration I'm on in the for loop due to scope. In this example, descriptionArray[0] will work, but descriptionArray[i] will not work because the for loop is outside the query.
Here is the entire logic:
//group data
var length = data2.Items[0].groupName.values.length;
// create elements
const dpdown1 = document.createElement('div');
// set dpdown1 class
dpdown1.setAttribute('class', 'dropdown');
console.log(dpdown1);
var button = new Array();
var dpdown2 = new Array();
var membersArray = new Array();
var descriptionArray = new Array();
var linksArray = new Array();
var stringy = new Array;
//list groups
for(i = 0; i<length; i++){
// create button, set button attribs
button[i] = document.createElement('button');
button[i].setAttribute('class','dropbtn');
//create dropdown div, set attributes
dpdown2[i] = document.createElement('div');
dpdown2[i].setAttribute('class', 'dropdown-content');
//list of group names
stringy[i] = data2.Items[0].groupName.values[i];
var stringyy = stringy[i];
var desc;
//query group members and description
var docClient1 = new AWS.DynamoDB.DocumentClient({ region: AWS.config.region });
var identityId = AWS.config.credentials.identityId;
var paramsyy = {
ExpressionAttributeValues: {
":v1": stringyy
},
KeyConditionExpression: "groupName = :v1",
TableName: "group"
};
docClient1.query(paramsyy, function(err, data2) {
if (err) {
console.error(err);
}else{
descriptionArray[0] = data2.Items[0].description;
//traverse members
for(k = 0; k<data2.Items[0].members.values.length; k++){
// create dropdown links of members
membersArray[k] = data2.Items[0].members.values[k];
linksArray[k] = document.createElement('a');
linksArray[k].setAttribute('href', '#')
linksArray[k].innerText = membersArray[k];
// nest into dpdown2 div, set dpdown2 attribs
dpdown2[0].appendChild(linksArray[k]);
}
}
});
button[i].innerText = stringyy + ": " + descriptionArray[0];
// nest into dpdown1
dpdown1.appendChild(button[i]);
dpdown1.appendChild(dpdown2[i]);
}
// append to DOM
const target = document.getElementById('target');
target.appendChild(dpdown1);
if I use the I from the first for loop inside the query function, it will give me undefined results.
here's how you can do it with vanilla JavaScipt, there are multiple ways to do it, but this way only uses 4 methods: createElement, setAttribute, appendChild, and getElementById, and directly sets 1 property: innerText.
// create elements
const dpdown1 = document.createElement('div');
const button = document.createElement('button');
const dpdown2 = document.createElement('div');
const link1 = document.createElement('a');
const link2 = document.createElement('a');
const link3 = document.createElement('a');
// set link attribs
link1.setAttribute('href', '#')
link1.innerText = 'Link 1';
link2.setAttribute('href', '#')
link2.innerText = 'Link 2';
link3.setAttribute('href', '#')
link3.innerText = 'Link 3';
// nest into dpdown2, set dpdown2 attribs
dpdown2.appendChild(link1);
dpdown2.appendChild(link2);
dpdown2.appendChild(link3);
dpdown2.setAttribute('class', 'dropdown-content');
// set button attribs
button.setAttribute('class','dropbtn');
button.innerText = "Dropdown"
// nest into dpdown1
dpdown1.appendChild(button);
dpdown1.appendChild(dpdown2);
// set dpdown1 class
dpdown1.setAttribute('class', 'dropdown');
// append to DOM
const target = document.getElementById('target');
target.appendChild(dpdown1);
<div id="target"></div>
You will to append it to something, in this example it's <div id="target"></div> but it could be something else.
Happy coding!
Mainly you are just doing things out of order.
Create the .dropdown <div> with its class.
Complete the .dropbtn <button> with its class and text.
Add the button to the div.
Create the .dropdown-content <div>.
Complete each link with its href attribute and text.
Add each link to the .dropdown-content <div>.
Add the .dropdown-content div to the .dropdown <div>.
Find the parent element in the document.
Append the whole complete .dropdown <div> to the document.
var para = document.createElement("div"); //make .dropdown div
para.setAttribute('class', 'dropdown'); //add .dropdown class to div
var button = document.createElement("button"); //create button
button.setAttribute('class', 'dropbtn'); //add .dropbtn class to button
var node = document.createTextNode('Dropdown'); //create button text
button.appendChild(node); //add text to button
para.appendChild(button); //add button to .dropdown div
var div = document.createElement("div"); //create .dropdown-content div
div.setAttribute('class', 'dropdown-content'); //add .dropdown-content class to div
//repeat for all necessary links
var alinky = document.createElement("a"); //creat link
alinky.setAttribute('href', '#'); //set link href attribute
var alinkyText = document.createTextNode("Link 1"); //create text for link
alinky.appendChild(alinkyText); //add text to link
div.appendChild(alinky); //add link to dropdown div
para.appendChild(div); //add .dropdown-content div to .dropdown div
var element = document.getElementById("parental"); //find parent element
element.parentNode.insertBefore(para, element.nextSibling); //add .dropdown div to the bottom of the parent element
<div id="parental">
</div>

Categories