const itemClicl = document.querySelector('.hiking__about_item_img');
const img1Element = document.querySelector('.img1');
const img2Element = document.querySelector('.img2');
itemClicl.onclick = imgToogle;
function imgToogle () {
const img1 = img1Element.getAttribute('src') === 'img/about_hiking/1.png';
const img2 = img2Element.getAttribute('src') === 'img/about_hiking/2.png';
if(img1) {
img1Element.src = 'img/about_hiking/2.png';
img1Element.setAttribute("alt", 'snowy mountains');
} else {
img1Element.src = 'img/about_hiking/1.png';
} img1Element.setAttribute("alt", 'house and mountains in the background')
if (img2) {
img2Element.src = 'img/about_hiking/1.png';
img1Element.setAttribute("alt", 'snowy mountains');
} else {
img2Element.src = 'img/about_hiking/2.png';
img1Element.setAttribute("alt", 'house and mountains in the background');
}
const clickTargetElement = document.querySelector('.hiking__about_item_img');
const imageConfigurations = {
primaryImage: {
htmlElement: document.querySelector('.img1'),
sourcePaths: ['img/about_hiking/1.png', 'img/about_hiking/2.png'],
altTexts: ['House and mountains in the background', 'Snowy mountains']
},
secondaryImage: {
htmlElement: document.querySelector('.img2'),
sourcePaths: ['img/about_hiking/1.png', 'img/about_hiking/2.png'],
altTexts: ['House and mountains in the background', 'Snowy mountains']
}
}
const toggleImageAttributes = ({htmlElement, sourcePaths, altTexts}) => {
const isPrimarySource = htmlElement.getAttribute('src') === sourcePaths[0];
const indexToUse = isPrimarySource ? 1 : 0;
htmlElement.setAttribute('src', sourcePaths[indexToUse]);
htmlElement.setAttribute('alt', altTexts[indexToUse]);
}
clickTargetElement.addEventListener('click', () => {
Object.values(imageConfigurations).forEach(toggleImageAttributes);
});
<div class="hiking__about_item_img">
<img class="img1" src="img/about_hiking/1.png" alt="House and mountains in the background">
<img class="img2" src="img/about_hiking/2.png" alt="Snowy mountains">
</div>
.hiking__about_item_img:not(.toggled) .img2,
.hiking__about_item_img.toggled .img1 {
display: none;
}
document.querySelector('.hiking__about_item_img')?.addEventListener('click', e => {
e.currentTarget.classList.toggle('toggled');
});