Having trouble displaying just one div at a time using jQuery

My webpage features a vertical list of items on the left side, contained within a <ul id="project_menu"> element. Whenever a user clicks on one of these items, a div called project-details is supposed to slowly fade in on the right side of the screen to display additional information. However, I encountered an issue where multiple divs are appearing simultaneously despite my efforts to ensure only one is displayed at a time.

Below are the key files involved:

<div class="project">
    <ul id="project_menu" class="project_menu">
        <li id="menu-php-mysql" data-projectID="php-project">PHP/MySQL</li>
        <li id="menu-nodejs" data-projectID="node-project">NodeJS</li> 
        <!-- more code -->
    </ul>
    <div class="project-detail">
        <div id="php-project">
            <i class="ion-ios-close-empty close-icon js-close-icon"></i>
            <div classs="project-text">
                <!-- data about project -->
            </div>
            <div id="node-project">
                <i class="ion-ios-close-empty close-icon js-close-icon"></i>
                <div classs="project-text">
                    <!-- data about project -->
                </div> 
                <!-- and so on.. -->
#php-project {
    background-color: #9b59b6;
    margin: 30px;
    display: none;
}
$(document).ready(function() {
    itemsToRender = [];
    $('ul#project_menu li').click(function(e) {
        menuItemId = (e.currentTarget.id);
        itemsToRender.push(menuItemId);
        var listSize = itemsToRender.length;              

        if (listSize > 1) {
            for (var i = 0; i < listSize - 1; i++) {
                currentItemId = itemsToRender[i];                
                $(getProjectId(currentItemId)).css('display', 'none');              
            }
            menuItemId = itemsToRender.pop();
            $(getProjectId(menuItemId)).fadeIn('slow');
        } else {
            $(getProjectId(menuItemId)).fadeIn('slow');
        }

        console.log(itemsToRender);
    });

    $('i.js-close-icon').click(function(e) { 
        projectId = (e.currentTarget.parentElement.id);
        console.log(projectId);    
        $('#' + projectId).fadeOut('slow');
    });
});

function getProjectId(menuItemId) {
    if (menuItemId.indexOf('php') > 0) { 
        return '#php-project';
    } else if (menuItemId.indexOf('node') > 0) {
        return '#node-project';
    } else if (menuItemId.indexOf('angular') > 0) {
        return '#angular-project';
    } else if (menuItemId.indexOf('mean') > 0) {
        return '#mean-project';
    }
}

In my attempt to address this issue, I created an array to store the item IDs clicked by the user, with the intention of hiding all corresponding divs except for the last one clicked. Despite implementing this logic, I am still facing challenges with multiple divs being visible simultaneously on the screen.

For instance, upon clicking on the PHP item, its respective div appears as expected. However, if I proceed to click on the NodeJS item, the PHP div should disappear while displaying the NodeJS div. But upon clicking back on the PHP item again, both divs start stacking up on each other rather than maintaining a single visible div. I am seeking insights on what might be causing this unexpected behavior.

Answer №1

If you want to make things simpler, just add the class .common to your items. Then, when you need to display a specific item like #id3, use the following code:

// when event xyz occurs....
jQuery(".common").hide();
jQuery("#id3").show();

To take it a step further, you can incorporate a callback function like this:

// when event xyz happens....
jQuery(".common").hide(function(){
 jQuery("#id3").show();
});

Answer №2

$('ul#project_menu li').click(function(e) {
   $project_id = $(this).attr("data-projectID"); //Retrieve the project id to display
   $(".all_projects").hide(); //Conceal all projects
   $("#"+$project_id).show(); //Reveal the last clicked project
}

Assign a shared class to all project divs. In this case, it is labeled as all_projects

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

The Mongoose framework has initiated a request to access the nested schema

I am puzzled as to why my database is not updating with my requests. I have a schema with nested objects, and I am trying to send a request to update a specific object within another object. The response indicates success, but nothing actually gets added t ...

Is there a way to access a div element that is present in the website's source code but does not appear in the visible document?

My goal is to create a Chrome extension that can categorize the people I follow on the website www.zhihu.com, since this feature is not available on the site itself. Upon inspecting the source code of the website, I noticed that my personal data is stored ...

Want to learn the process of closing a modal using Javascript?

I am working on implementing 6 different modals, each featuring an exit button named 'modal-box__exit-button'. I have attempted to use JavaScript to close the modals when the exit button is clicked, but it seems like my code may have some errors. ...

Google Chrome encountered an uncaught RangeError with jQuery due to exceeding the maximum call stack size

I originally had this code: jQuery('.views-row').each(function(){ if(jQuery(this).find('.views-field-field-doctor-indicator').length != 0) { jQuery(this).css("padding","0px"); jQuery('.views-field-title span a& ...

Modify PHP script to extract the Document Object Model (DOM) from a specified URL

Hey there, I'm currently using this code to extract and display the HREFs of all "A" tags from a URL. However, my output includes the entire link when I only want the name portion after http://twitter.com/namehere So, I'm looking to clean up my ...

What is the best way to invoke a Rest API within a Vue component?

As a newcomer to VueJS, my goal is to create a basic page featuring a pie chart displaying some data. Currently, I have successfully displayed the chart using example data. However, I now wish to populate the chart with data fetched from an API call on my ...

Challenge with creating instances of a Javascript class

I'm currently delving into JavaScript OOP and have encountered an issue. While my code successfully works to change a class variable for a specific instance, it fails when I try to print the updated value in an event handler. Initially setting "mynam ...

Run JavaScript code last before page unloads

Two pages are involved in this process. On the first page, there is a form that the user completes and then clicks on the submit button. After that, the code for the first page unloads, and the user is redirected to the second page. Actual Issue A loadin ...

Using the `setDate` function in jQueryUI datepicker will remove the time component from the selected date

Is there a bug in jQuery UI? I noticed that when I use .datepicker('setDate', date); and the date object includes a time component, the datepicker sets the time to 0:00. Even if I try cloning the variable... var datewithtime = new Date(); var l ...

Trouble with triggering HTML5 FileReader() functions

I'm having trouble determining why neither readSuccess() nor readFailure() are being executed in the code snippet below: function readMyFile(){ var reader = new FileReader(); reader.onload = readSuccess; reader.onerror = readFailure; ...

Passing props to children in the Next JS Layout component is a crucial aspect of

I recently came across a code snippet that effectively resolved my re-rendering issue in Next JS when switching pages. However, I am now faced with the challenge of sending props to the children component. In my layout.js file, I have managed to send props ...

Initiating an Ajax request to a Controller results in a 404 error

Whenever I make an Ajax call to a Controller method, I encounter the following error message: http://localhost:55942/ "GetCalculateAmortizationSchedule", "Home" 404 (Not Found) The Controller method looks like this: [HttpPost] public ActionResult ...

Decide which characteristics to serialize

When converting a div into a string using new XMLSerializer().serializeToString(), I want to be able to select specific DOM attributes for serialization. For instance: let element1 = document.getElementById('element1'); element1.style.colo ...

How can elements with class prefix names be retrieved in IE Browser Helper Object using c#?

I've been developing an IE Plugin using BHO and I need to access an element based on its class prefix in C#. In JavaScript and jQuery, I was able to accomplish this with the following code: var myClass = $('[class^="ii gt"]'); and var myC ...

What is the best method for getting rid of blank white space on my website?

Having some trouble removing unnecessary white space on my website. The goal is to have the main text and logo centered on an image background, but I've been unsuccessful so far. I've experimented with different CSS properties like overflow-x: ...

When you try to click outside of react-select, the dropdown doesn't

I've been working on customizing react-select and encountered some issues. Specifically, after modifying the ValueContainer and SelectContainer components, I noticed that the dropdown doesn't close when clicking outside of it after selecting a va ...

Surprising array behavior encountered when using JSON.stringify on a particular site

I'm currently utilizing the JSON3 library, but I'm facing an issue where JSON.stringify is returning different results on a particular website. Unfortunately, the website requires login access, but I have included images for reference. If someon ...

Get the input value and display it on the PHP page

I've been struggling for hours trying to figure out how to read the value from an input box in HTML and use it to dynamically create dropdown boxes using PHP within the same file. Despite my efforts, I haven't been able to find a working solution ...

What is the best way to show and hide text by toggling a link instead of a button?

I need help with toggling between two different texts when a link is clicked. I know how to achieve this with a button in JQuery, but I'm not sure how to do it with a link. <h1>Queries and Responses</h1> <p>Query: What is the larges ...

Sliding HTML tabs for easy navigation

Is there a way to display multiple tabs in a limited space by using arrows to toggle between hidden tabs? Or perhaps by dragging the tab strip back and forth as needed? Imagine having 10 tabs but only room for 5 to be visible: Tab 1 Tab 2 Tab 3 Tab 4 ...