Reputation: 65
I have a list of image in index file as below:
<div id="image-list"
<ul>
<li data-id='1'>
<img src='image/001.jpg' alt=''>
</li>
<li data-id='2'>
<img src='image/002.jpg' alt=''>
</li>
<li data-id='3'>
<img src='image/003.jpg' alt=''>
</li>
</ul>
</div>
And I made an click event for image list:
document.getElementById("image-list").addEventListener('click', function(){
if(document.getElementById("background").style.backgroundImage == 'url("image/001.jpg")'){
console.log("I clicked in the image 001");
}
if(document.getElementById("background").style.backgroundImage == 'url("image/002.jpg")'){
console.log("I clicked in the image 002");
}
if(document.getElementById("background").style.backgroundImage == 'url("image/003.jpg")'){
console.log("I clicked in the image 003");
}
});
But I have issue load wrong url. When I am in image 001 and click on image 002, the function above show log "I clicked in the image 001" instead of "I clicked in the image 002" as I expect.
Anyone can help me give a right function that when I click on image 002, the console log print "I clicked in the image 002" as I expect. Thanks.
Upvotes: 1
Views: 1187
Reputation: 68933
You should target all the images then loop through them and attach the event. Inside the event handler function get the src
attribute and match that.
Demo:
document.querySelectorAll("#image-list ul > li > img").forEach(function(el){
el.addEventListener('click', function(){
var src = this.getAttribute('src');
if(src == "image/001.jpg"){
console.log("I clicked in the image 001");
}
else if(src == "image/002.jpg"){
console.log("I clicked in the image 002");
}
else if(src == "image/003.jpg"){
console.log("I clicked in the image 003");
}
});
});
<div id="image-list">
<ul>
<li data-id='1'>
<img src='image/001.jpg' alt='11'>
</li>
<li data-id='2'>
<img src='image/002.jpg' alt='22'>
</li>
<li data-id='3'>
<img src='image/003.jpg' alt='33'>
</li>
</ul>
</div>
Upvotes: 2