<div class = "category_list_11">
<img src = "./static/images/compre6.png" class = "coffeeimages">
<div class = "category_list_field">
<div class = "category_list_field1">
<button class = "categoryfieldbutton1">
<img src = "./static/images/hm_favorite_2.png" class = "favorite_img1">
</button>
</div>
<div class = "category_list_field2">
<button class = "categoryfieldbutton2">
<img src = "./static/images/hm_2_cart_2.png" class = "favorite_img2">
</button>
</div>
</div>
</div>
in javascript i tried to add event listener for category_list_field_1
var categoryfields = Array.from(category_list_field);
for (let i = 0; i < categoryfields.length; i ) {
categoryfields[i].addEventListener("click", event => {
console.log(event.target.matches(".favorite_img2"))
if(event.target && event.target.matches(".favorite_img2")) {
console.log(event.target.src);
if (event.target.src = "static/images/hm_2_cart_2.png") {
console.log("1");
event.target.src = "static/images/hm_2_cart_2_a.png";
console.log(event.target);
}
if (event.target.src = "static/images/hm_2_cart_2_a.png") {
event.target.src = "static/images/hm_2_cart_2.png";
}
I want to make event listener which would make image with class "favorite_img2" change src on click to "hm_2_cart_2_a.png" then go back to previous src on next click. The line
console.log(event.target);
gives the output <img src="static/images/hm_2_cart_2.png" class="favorite_img2">
Sorry for the dreadful formatting. Thank you very much in advance.
CodePudding user response:
Your problem is most likely this line
if (event.target.src = "static/images/hm_2_cart_2.png")
inside the parenthesis there should be a comparison operator, instead you are assigning the .src
which will always be true. You need to use the double equal sign ==
to compare the src to a string.