Is it possible to add a click event to an image?
Is it possible to add a click event to an image?
I have an image and I want it to add a list item to the UL when it's clicked. It's not working.
HTML and JavaScript are as follows:
const myList = document.querySelector('ul');
const imageClick = document.getElementById('test');
imageClick.addEventListener('click',() =>
myList.innerHTML = '<li>This goes on the list</li>';
);
<ul class='list'>
</ul>
<img src ='imgs/test.jpeg' alt = 'an image'
id='test'>
I'd create a JSFiddle but I'm not sure how to add dummy images and show any of value that would explain it better.
Lots of sources on web for placeholder images that can quickly be used to create a demo
– charlietfl
Aug 27 at 14:00
My javascript is linked before the closing of my body tag.
– YoungSherlock
Aug 27 at 15:14
1 Answer
1
const myList = document.querySelector('ul');
const imageClick = document.getElementById('test');
imageClick.addEventListener('click',() =>
myList.innerHTML += '<li>This goes on the list</li>';
);
I changed the image src
to the following:
src
<img src ='https://placeholder.pics/svg/300x300' alt = 'a kid covered in paint' id='test'>
I've created a working example for you here:
http://jsfiddle.net/06kgze4y/1/
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
That should work, you just need to make sure that your javascript is after your html unless you are using onload method to attach event.
– Senad Meškin
Aug 27 at 13:59