Issue
I'm trying to create a gallery with a main image and smaller images below,by clicking on the main image it should open it in a new window, and if you click smaller one, it should change the main image to that you cliked and it also change href, so in the end, main image is dynamicly changing href and src attributes.
Below you could see how I try to do this, it's working, but when i press smaller images, they not only change the main one, but also opens in the new window. What should I do, so only main image could open new window?
function transitSrc(imgs) {
// Get the expanded image
var expandImg = document.getElementById("expandedImg");
// Use the same src in the expanded image as the image being clicked on from the grid
expandImg.src = imgs.src;
//Get the href of expanded image
var fullImage = document.getElementById("viewFullImg");
//Use the same href in the expanded image as the image being clicked on from the grid
fullImage.href = imgs.href;
// Show the container element (hidden with CSS)
expandImg.parentElement.style.display = "block";
}
.product-gallery {
list-style: none;
padding: 0;
width: 100%;
margin: 10px 0 0;
}
.product-gallery li {
display: inline-block;
width: 15%;
margin: 0 5px;
}
.product-gallery li:first-child {
margin-left: 0;
}
<div class="container">
<div class="row">
<div class="col-sm-6 mb-sm-40">
<div class="gallery">
//main image
<a id="viewFullImg" href="https://picsum.photos/id/1060/536/354?blur=2">
<img id="expandedImg" src="https://picsum.photos/id/1060/536/354?blur=2" style="width:50%">
</a>
</div>
//smaller images
<ul class="product-gallery">
<li>
<a href="https://picsum.photos/id/870/536/354?grayscale&blur=2"> <img style="width:80%" src="https://picsum.photos/id/870/536/354?grayscale&blur=2" onclick="transitSrc(this);"></a>
</li>
<li>
<a href="https://picsum.photos/id/1060/536/354?blur=2"> <img style="width:80%" src="https://picsum.photos/id/1060/536/354?blur=2" onclick="transitSrc(this);"></a>
</li>
<li>
<a href="https://picsum.photos/id/870/536/354?grayscale&blur=2"> <img style="width:80%" src="https://picsum.photos/id/870/536/354?grayscale&blur=2" onclick="transitSrc(this);"></a>
</li>
</ul>
</div>
</div>
</div>
Solution
To obtain your desired behavior, you could use one of two approach:
- Remove the
a
tag - Keep the tag and prevent its default behavior
The first method it's pretty straight forward, while, to prevent the a
tag to do the redirect, you could override onClick
preventing its default behavior:
function prevent(event) {
event.preventDefault();
}
<a href="https://stackoverflow.com" onClick="prevent(event)">Press here</a>
Answered By - CcmU
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.