My objective:
- I want to display a set of thumbnails.
- When a thumbnail is clicked, I want to toggle the hiddenElement class and show a large image inside a hidden div.
- If anywhere in the DOM is clicked, it should hide the current image or allow the user to switch to the next div (if that div's second thumbnail is clicked).
The Issue I'm Facing: The image toggles correctly when clicked on or in the DOM, except when clicking on the second or third thumbnail. It keeps the original image visible and loads the next clicked image below it, leaving both images displayed simultaneously.
For example, clicking on the first thumbnail displays its image, but then clicking on the second thumbnail fails to hide the first image and instead loads the second image alongside it. The intended behavior is for the CSS class hiddenElement to be toggled.
My jQuery Code:
$("#port1_thumb, #port1_large").on("click", function() {
$("#port1_thumb, #port1_large").toggleClass("hiddenElement");
});
$('document').click(function() {
$('#port1_large').removeClass('hiddenElement');
});
$("#port2_thumb, #port2_large").on("click", function() {
$("#port2_thumb, #port2_large").toggleClass("hiddenElement");
});
$('document').click(function() {
$('#port2_large').removeClass('hiddenElement');
});
The Structure of My Document Object Model (DOM):
<div class="wrap">
<!-- Hidden elements -->
<div id="port1_large" class="hiddenElement">
<img src="assets/portfolio-images/portfolio_content/project1.jpg">
</div>
<div id="port2_large" class="hiddenElement">
<img src="assets/portfolio-images/portfolio_content/project2.jpg">
</div>
<!-- /Hidden elements -->
<!-- Thumbnails -->
<div id="portfolio">
<ul class="portfolio-grid">
<li>
<a id="port1_thumb" target="portfolio">
<img src="assets/portfolio-images/portfolio_thumbnails/thumbnail_1.png" alt="img01"/>
<h3>Project 1</h3>
</a>
</li>
<li>
<a id="port2_thumb"
target="portfolio">
<img src="assets/portfolio-images/portfolio_thumbnails/thumbnail_2.png" alt="img01"/>
<h3>Project 2</h3>
</a>
</li>
</ul>
</div>
</div>
The CSS Class Used:
.hiddenElement {
display: none;
}
Additional Information:
I notice that my code has a lot of repetition, causing issues with toggleClass. How can I simplify my code to avoid this problem?
I suspect the problem stems from repeatedly applying the same action to the same class in my jQuery script, but I am unsure how to refactor it.
I came across a JSFiddle demonstrating a similar issue, where switching between thumbnails does not work as expected.
If there are any tutorials or discussions addressing the specific topic of toggleClass malfunctioning with multiple elements, please share them.
Thank you for your assistance.