The functionality of jQuery's toggleClass is not functioning properly when clicking on a different thumbnail

My objective:

  1. I want to display a set of thumbnails.
  2. When a thumbnail is clicked, I want to toggle the hiddenElement class and show a large image inside a hidden div.
  3. 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.

Answer №1

For a solution that aligns with your needs, consider implementing the following code snippet:

<head>
    <title></title>
    <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script>
    <style>
        .hiddenElement {
            display: none;
        }
    </style>
</head>
<body>
    <div class="wrap">

        <div id="port1_large" class="hiddenElement large">
        <img src="assets/portfolio-images/portfolio_content/project1.jpg">
    </div>

    <div id="port2_large" class="hiddenElement large">
        <img src="assets/portfolio-images/portfolio_content/project2.jpg">
    </div>

    <div id="portfolio">
        <ul class="portfolio-grid">
            <li>
                <a id="port1_thumb" class="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" class="thumb"
                    target="portfolio">
                    <img src="assets/portfolio-images/portfolio_thumbnails/thumbnail_2.png" alt="img01" />
                    <h3>Project 2</h3>
                </a>
            </li>
        </ul>
    </div>
    </div>
    <script>
       
        $("#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");
        });

        $("#port1_thumb").click(function ()
        {
            if (!$('#port2_large').hasClass("hiddenElement"))
                $('#port2_large').addClass("hiddenElement");
            $("#port2_thumb").removeClass("hiddenElement");
        });

        $("#port2_thumb").click(function ()
        {
            if (!$('#port1_large').hasClass("hiddenElement"))
                $('#port1_large').addClass("hiddenElement");
            $("#port1_thumb").removeClass("hiddenElement");
        });

        $('document').click(function ()
        {
            $('#port2_large').removeClass('hiddenElement');
        });
    </script>
</body>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Vanishing Act: Bootstrap menu vanishes after a click

Having difficulties with the menu on my website wrapster.sebastianbialek.pl. Whenever I resize the browser to mobile version and click on the collapse button, the menu shows up briefly and then disappears. Any assistance in resolving this issue would be gr ...

Does the padding and margin of an element alter when the position is set to relative?

By utilizing relative positioning, an element can be moved in relation to its original position in normal flow. - Citation from the book "HTML&CSS: design and build websites" by John Duckett If an element has a relative position property, it opens up ...

Three fixed position divs arranged horizontally side by side

I am attempting to organize 3 divs in a row using Flex. ISSUE 1: The div that is centered is set with position: fixed. However, the two other divs on each side do not stay aligned with the centered fixed div when scrolling. If I change the centered div to ...

What steps can be taken to address the error message "FATAL: Unable to load template" encountered while using

I'm encountering the issues documented here and here on GitHub. I'm working on incorporating documentation for my Next.js code, and below is my jsdoc configuration file. { "tags": { "allowUnknownTags": true, "di ...

Looking for advice on using the ternary operator in your code? Let us

In my JS file, the code $scope.button = id ? "Edit" : "Add"; is functioning correctly. I am trying to implement it in the View like this: <button name="saveBtn" class="btn btn-primary" tabindex="10">{{person.id ? 'Edit' : 'Add&ap ...

The function $.post(...) is failing to detect the JSON content in the

I am attempting to send a POST request to the server using the following code: var body = { PatientAgeFilter: { CompareOperator: parseInt(self.patientAge()), MoreThanVal: { AgeSpecifier: 0, AgeValue: parseInt(se ...

Tips for updating parent data with multiple values from a child component

Check out the code snippet below. I seem to be stuck on a crucial component. Despite going through the documentation and watching tutorials on Vue2, I can't seem to grasp this key element. Any assistance would be greatly appreciated. If my approach i ...

Arranging Cards in Layers on Smaller Screens Using Bootstrap Framework

My row of cards in various sizes looks good on larger screens like this: https://i.sstatic.net/1qF53.png However, on smaller screens, the cards lose their appeal. https://i.sstatic.net/o1NS8.png To improve this, I want to stack the cards so that the ke ...

Achieving a perfect circle can be accomplished by setting both the width and height to the same

Trying to make the height of an element equal to its width For example, aiming for a perfect circle Although the console displays equal values, the resulting height is noticeably greater than the width $('button').on('click', funct ...

get the data from a database table by specifying the ID and retrieve the corresponding column value

I am struggling to retrieve the value of a database column based on its ID. My goal is to show it in a <span> with the ID "#name_page" I pass the ID via POST using "$(this).attr("id")" This is my AJAX request $(document).on('click', &apo ...

Having issues with using setTimeOut within a for loop in JavaScript React

I'm currently working on a visual sorting algorithm application using React. My implementation involves bubble sort, where I generate an array of numbers from 1 to 50, shuffle them, and then apply the bubble sort method to sort them. However, I am fac ...

Looking to create a custom loader that adapts to different screen sizes

Can anyone help me make the text in my centered div responsive on my website loader? I'm new to coding and struggling to figure it out. Any assistance would be greatly appreciated! Make sure to view the full page snippet so you can see the text prope ...

Challenges with Organizing Data and Maintaining Database Integrity

I have been working on making this sortable code function properly. Initially, I had it working fine with <li> elements as shown in the UI examples. However, now I am trying to implement it with <div> elements. While it shouldn't be much o ...

Increase the size of the grid system column upon clicking on a Bootstrap icon

I am using Google Maps in a tab with Bootstrap, but the map is too small. I would like to change the Bootstrap grid system when I click on a FontAwesome icon: the first column should turn into col-md-8, and the second column should become col-md-4. Here i ...

Unable to interact with web element using JavaScript

Struggling to find a solution for simulating a click on a button element on Outlook.com mobile website using JavaScript. Despite numerous attempts from online sources, the button remains unresponsive to clicks. An interesting discovery was made that the c ...

Node.js Buffer problem: How to tackle it

Encountering an issue with buffers in Node.js The constant buffer is defined as follows: var commands = { BufferOne : new Buffer([0XCA, 0X11, 0X00, 0X00, 0X60, 0X01, 0X00, 0X01, 0X08, 0X07, 0X6D, 0X00, 0X00, 0X00, 0X00, 0 ...

List-style-type outside of a table's boundaries

I recently experimented with using <ol> as list elements within a table in order to dynamically insert new table rows. <table> <thead> <tr> <th>head</th> <th>head</th> <th>h ...

Revitalizing HTML and Google Maps with AJAX, PHP, and JQuery

Context: I am currently working on a project that involves integrating a Simple Google Map with an HTML form right below it. The form collects user input and upon submission, sends the data via AJAX to a PHP script for processing API calls and generating i ...

Angular.js and DAO design pattern

Admitting my newness to Angular.js and lack of experience with frameworks like Backbone or Knockout, I am venturing into building an application that interacts with a server using a RESTful API. After delving deep into the angular documentation and blog po ...

Transform JSON data into a JavaScript variable

Just diving into the world of Node.js and JavaScript. Please forgive me if my question seems basic. Here is a snippet of my Node.js code that retrieves data from MySQL: var quer = connection.query('select password from users where mail="' ...