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)
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>
First you check if the target
(ie the element that is clicked) has the tooltip class
event.target.classList.contains('tooltip')
But then you use the currentTarget
(ie 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.