0

I'm looking for a way to set the src of an image - in a modal - using the data attribute of a clickable element.

The markup for the element looks like this (there could be multiple of these on a page):

<span class="tooltip" data-imageToSet="someimage.jpg">Click me</span>
<div id="modal">
  <img id="image" src="placeholder.jpg" />
</div>
<script>
  var modal = document.getElementById('modal'),
    modalImage = document.getElementById('image');

  document.addEventListener('click', function(event) {
    if (event.target.classList.contains('tooltip')) {
      modal.classList.toggle('shown');
      modalImage.src = event.currentTarget.dataset.imageToSet;
    }
  });
</script>

From what I've been reading up, this should work? But I keep getting a console error:

Uncaught TypeError: Cannot read property 'imageToSet' of undefined at HTMLDocument.<anonymous> ((index):1)
4
  • console.log(event.currentTarget) Commented Mar 3, 2020 at 20:14
  • Tip: Why don't you bind the addEventListener directly on the tooltip element? Commented Mar 3, 2020 at 20:19
  • @KostasX when you have multiple elements.... Basics of event delegation Commented Mar 3, 2020 at 20:19
  • Oh, yes. I was looking at the code and forgot about the 'multiple' part in the description. Thanks @epascarello. Commented Mar 3, 2020 at 22:26

2 Answers 2

1

You have two issues. currentTarget will be the element you bound the click to so it will be document. The second issue is camel case does work with dataset, you need to use dash.

var modal = document.getElementById('modal'),
  modalImage = document.getElementById('image');

document.addEventListener('click', function(event) {
  if (event.target.classList.contains('tooltip')) {
    modal.classList.toggle('shown');
    console.log(event.target)
    modalImage.src = event.target.dataset.imageToSet;
  }
})
<span class="tooltip" data-image-to-set="http://placekitten.com/300/300">Click me</span>


<div id="modal">
  <img id="image" src="http://placekitten.com/g/200/300" />
</div>

Sign up to request clarification or add additional context in comments.

Comments

0

First you check if the target (i.e. the element that is clicked) has the tooltip class

event.target.classList.contains('tooltip')

But then you use the currentTarget (i.e. the element to which the event handler is bound: document) to read the dataset.

modalImage.src = event.currentTarget.dataset.imageToSet

You need to continue to use the target throughout.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.