My latest project involves a meme generator that allows users to input text and images, which are then combined to create a unique 'meme'. Each meme is assigned a unique ID and features buttons for deleting the meme upon hovering. To achieve this functionality, I utilized vanilla JS and layered multiple child divs (image, top text, bottom text) using z-index.
Despite my efforts, I'm facing challenges with enabling the delete button to remove the parent div on click. I aim to have the delete button effectively remove the entire meme - image, text, and button itself. You can view an example picture and code snippets below:
https://i.sstatic.net/dIJWP.jpg
I attempted to implement the deletion feature in vanilla JavaScript by assigning a 'closeTheMeme' function to each delete 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 were reported in the console. Below, you'll find the remaining JavaScript code depicting how elements are generated upon clicking 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 texts to variables for manipulation
let bottomText = document.getElementById('bottomText').value;
createMeme();
})
function createMeme(){
let meme = document.createElement("DIV");
document.body.appendChild(meme);
meme.setAttribute("id", "meme"+count);
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;
let topText = document.getElementById('topText').value;
let top = document.createElement('DIV');
top.setAttribute("id","topText"+ count);
meme.appendChild(top);
top.innerHTML = topText;
let bottomText = document.getElementById('bottomText').value;
let bottom = document.createElement('DIV');
bottom.setAttribute("id","bottomText" + count);
meme.appendChild(bottom);
bottom.innerHTML = bottomText;
let deleteButton = document.createElement("BUTTON");
deleteButton.classList.add("delete");
deleteButton.innerHTML = "Delete";
meme.appendChild(deleteButton);
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);
}