for example, all images are hidden and when I click list, it should pop up. if I click "Hello1" text then image1 should popup
<li class nav-1><a href="#">Hello1</a></li>
<li class nav-1><a href="#">Hello2</a></li>
<li class nav-1><a href="#">Hello3</a></li>
<img src="images/1.jpg" alt=""/>
<img src="images/2.jpg" alt=""/>
<img src="images/3.jpg" alt=""/>
CodePudding user response:
I would add id's to your images and put in a basic hide/unhide script:
<script>
function toggleHide(elementid){
a=document.getElementById(elementid).style.visibility;
if (a=="hidden"){
document.getElementById(elementid).style.visibility="visible";
}else{
document.getElementById(elementid).style.visibility="hidden";
}
}
</script>
<style>
/* hide all images */
#img1{
visibility:hidden;
}
#img2{
visibility:hidden;
}
#img3{
visibility:hidden;
}
</style>
<li class nav-1><a href="#" onclick="toggleHide('img1')">Hello1</a></li>
<li class nav-1><a href="#" onclick="toggleHide('img2')">Hello2</a></li>
<li class nav-1><a href="#" onclick="toggleHide('img3')">Hello3</a></li>
<img src="images/1.jpg" id="img1" alt=""/>
<img src="images/2.jpg" id="img2" alt=""/>
<img src="images/3.jpg" id="img3" alt=""/>
CodePudding user response:
In the example below, I used div
instead of img
, but the concept is the same...
Read the comments for more details please:
// Get the buttons and the images
let buttons = document.querySelectorAll('.btn');
let images = document.querySelectorAll('.image');
// For each button:
buttons.forEach(btn => {
// Onclick event:
btn.addEventListener('click', () => {
// Get all the images and remove the 'active' class
images.forEach(image => { image.classList.remove('active'); });
// Get the id of the clicked button (which is the data-image of the target image)
let target = btn.getAttribute('id');
// Add the class 'active' to the image
document.querySelector(`[data-image="${target}"]`).classList.add('active');
});
});
.image {
width: 100px;
height: 100px;
border: 1px solid;
opacity: 0;
transition: all 0.2s;
display: none;
}
.image.active {
opacity: 1;
display: block;
}
<button class="btn" id="image1">Image 1</button>
<button class="btn" id="image2">Image 2</button>
<button class="btn" id="image3">Image 3</button>
<div class="image" data-image="image1">1</div>
<div class="image" data-image="image2">2</div>
<div class="image" data-image="image3">3</div>