I couldn't for the life of me figure this out! How can I make this happen - When image is clicked set opacity to 1 and lower opacity for other images? I was told to add a class to the clicked image, store it, then remove the class when another image is clicked? but i cant figure it out!
let items = document.getElementsByClassName("item");
document.body.addEventListener('click', (event) => {
const el = event.target;
for(var i=0; i< smallImg.length; i ) {
if (el.className !== 'sec') return;
const wasSelected = el.classList.contains('selected');
for (const d of document.querySelectorAll('div >img'))
d.classList.remove('selected');
el.classList.toggle('selected', !wasSelected)
console.log(".selected");
}
});
.sec:not(:first-child) {
opacity: 0.3;
}
.sec:not:active{
opacity: 0.3;
}
<div >
<img
src="https://source.unsplash.com/400x400/?stationery"
/>
<div >
<img
src="https://source.unsplash.com/100x100/?pen"
/>
<img
src="https://source.unsplash.com/100x100/?pencil"
/>
<img
src="https://source.unsplash.com/100x100/?notepad"
/>
<img
src="https://source.unsplash.com/100x100/?eraser"
/>
</div>
CodePudding user response:
Just select the element that currently has the active
class, and if such an element exists, remove that class from that. And then add it to the one that was clicked.
(Any check on whether the clicked element was actually one of those images, is not currently included. I simply kept your general click handler for body
, please refine this yourself to apply only where needed.)
document.body.addEventListener('click', (event) => {
let el = event.target;
let prev = document.querySelector('.secondary-image .active');
if(prev) {
prev.classList.remove('active');
}
el.classList.add('active');
});
.secondary-image .sec:not(.active) {
opacity: 0.3;
}
<div >
<img
src="https://source.unsplash.com/400x400/?stationery"
/>
<div >
<img
src="https://source.unsplash.com/100x100/?pen"
/>
<img
src="https://source.unsplash.com/100x100/?pencil"
/>
<img
src="https://source.unsplash.com/100x100/?notepad"
/>
<img
src="https://source.unsplash.com/100x100/?eraser"
/>
</div>