Dynamically add a div around image submitted from a URL form

Viewed 38

First of all, very new to javascript and coding in general here so apologies for that. I am appending a new image from a URL submitted from a form. I need to dynamically add a div to the image when it is loaded into the DOM so I can ultimately add some text to the top and the bottom of the image. This is for a meme generator style app. Not sure if the remove logic at the end is pertinent but I will include it just in case. Thanks in advance!

form.addEventListener('submit', function(e) {
e.preventDefault();

let newMeme = new Image(470, 300);
newMeme.src = imageURL.value;
newMeme.setAttribute('class', 'memeStyle');
memeDiv.appendChild(newMeme);
imageURL.value = '';

newMeme.addEventListener('click', function(e) {
    newMeme.remove(e.target);
    console.log(e.target);
});

});

1 Answers

Something in the lines of this:

form.addEventListener('submit', function(e) {
  e.preventDefault();
  
  // Create the image
  const newMeme = new Image(200, 130);
  newMeme.src = imageURL.value;
  newMeme.setAttribute('class', 'memeStyle');
  
  // Create a top caption
  const topCaption = document.createElement('p');
  topCaption.appendChild(document.createTextNode('TOP CAPTION'));
  // Create a botom caption
  const bottomCaption = document.createElement('p');
  bottomCaption.appendChild(document.createTextNode('BOTTOM CAPTION'));
  
  // Add stuff to the wrapper
  memeDiv.appendChild(topCaption);
  memeDiv.appendChild(newMeme);
  memeDiv.appendChild(bottomCaption);
  
  imageURL.value = '';

  newMeme.addEventListener('click', function(e) {
    memeDiv.innerHTML = '';
  });
});
#memeDiv {
  float: left;
  position: relative;
}
#memeDiv p {
  position: absolute;
  left: 0;
  width: 100%;
  margin: 4px;
  text-align: center;
  color: #fff;
  font-weight: bold;
  font-family: Arial, Helvetica, sans-serif;
  text-shadow:
   -1px -1px 0 #000,  
    1px -1px 0 #000,
    -1px 1px 0 #000,
     1px 1px 0 #000;
}
#memeDiv p:first-of-type { top: 0; }
#memeDiv p:last-of-type { bottom: 0; }
<form id="form">
  <input id="imageURL" value="https://res.cloudinary.com/sagacity/image/upload/c_crop,h_1001,w_1500,x_0,y_0/c_limit,dpr_auto,f_auto,fl_lossy,q_80,w_1080/Kitten_murder_Jeff_Merkley_2_copy_hdpoxd.jpg">
  <input type="submit" value="Submit"> ← Hit submit
</form>

<div id="memeDiv"></div>

Related