So, I don't have any working knowledge of JavaScript, but I am wondering why this does not work for me. I have 4 buttons, 4 different divs with different images, when one button is clicked I would like the images to change to the category which is displayed on the button.
i.e Button: "Windows" --Button is clicked--> Show images of windows
Button "Doors" --Button is clicked--> show images of Doors
JavaScript file is imported to HTML document:
<head>
<script type="text/javascript" src="script.js"></script>
</head>
const showChoosenCategory = event => {
const getId = event.id
const links = document.querySelectorAll('.work-category button')
for (i = 0; i < links.length; i++) {
if (links[i].hasAttribute('class')) {
links[i].classList.remove('active')
}
}
event.classList.add('active')
const getCategory = document.querySelector(`.category-${getId}`)
const categories = document.querySelectorAll('div[class ^= "category-"]')
for (i = 0; i < categories.length; i++) {
if (categories[i].hasAttribute('class')) {
categories[i].classList.remove('showCategory')
categories[i].classList.add('hideCategory')
}
}
getCategory.classList.remove('hideCategory')
getCategory.classList.add('showCategory')
}
.hideCategory {
display: none;
}
<div class="gallery" id="gallery">
<div class="work-category">
<button class="category active" id="windows">F?nster</button>
<button class="category" id="doors">D?rr</button>
<button class="category" id="furniture">M?bler</button>
<button class="category" id="misc">?vrigt</button>
</div>
<div class="category-windows showCategory">
<div class="imageslist">
<img src="assets/img_window.jpg" class="gallery-image">
</div>
</div>
<div class="category-doors hideCategory">
<div class="imageslist">
<img src="assets/img_door.jpg" class="gallery-image">
</div>
</div>
<div class="category-furniture hideCategory">
<div class="imageslist">
<img src="assets/img_furniture.jpg" class="gallery-image">
</div>
</div>
<div class="category-misc hideCategory">
<div class="imageslist">
<img src="assets/img_misc.jpg" class="gallery-image">
</div>
</div>
</div>
question from:https://stackoverflow.com/questions/66050288/show-different-images-onclick-event-javascript