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.





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





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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Crossroads (UK TV series)

ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế