Reputation: 347
I got images with same width and height and onclick
they should get bigger, so I made an function with an eventlistener
for it but now it tells me that style isn't defined and I don't see the issue. I set the styles inside the img
tag and also without style.
<img class="painting" src="<%= post.paintingsP %>" />
<img class="painting" style="max-width: 20%; min-width: 300px; height: 250px;"src="<%= post.paintingsP2 %>" />
js file
const paint = document.getElementsByClassName('painting');
let flag = true;
for (var i = 0; i < paint.length; i++) {
paint[i].style.maxWidth = '20%';
paint[i].style.height = '250px';
paint[i].style.minWidth = '300px';
paint[i].addEventListener('click', () => {
if (flag == true && window.innerWidth >= 769) {
paint[i].style.maxWidth = '95vw';
paint[i].style.height = 'auto';
flag = false;
} else if (flag == true && window.innerWidth < 769) {
} else {
paint[i].style.maxWidth = '20%';
paint[i].style.minWidth = '300px';
paint[i].style.height = 'auto';
flag = true;
}
})
}
If I try to use getelementById
everything works fine but I don't want for every image an eventlistener
.
Upvotes: 0
Views: 66
Reputation: 817
Use event.target
in the eventlistener function to find the clicked image.
const paint = document.getElementsByClassName('painting');
let flag = true;
for (var i = 0; i < paint.length; i++) {
paint[i].style.maxWidth = '20%';
paint[i].style.height = '250px';
paint[i].style.minWidth = '300px';
paint[i].addEventListener('click', (event) => {
console.log(event.target)
if (flag == true && window.innerWidth >= 769) {
event.target.style.maxWidth = '95vw';
event.target.style.height = 'auto';
flag = false;
} else if (flag == true && window.innerWidth < 769) {
} else {
event.target.style.maxWidth = '20%';
event.target.style.minWidth = '300px';
event.target.style.height = 'auto';
flag = true;
}
})
}
<img class="painting" src="<%= post.paintingsP %>" />
<img class="painting" style="max-width: 20%; min-width: 300px; height: 250px;"src="<%= post.paintingsP2 %>" />
Upvotes: 1