Steps for making a toggle button that switches panels

Within my application, there are 2 toggle buttons and 3 panels. Button1 toggles between panel 1 and 2, while button2 switches between panel 1 and 3. I managed to make them work by setting the display: none; property to div panels, but after one use of each button, all sub divs are hidden. Here is a sample:

$(function () {
  $("button.panel2").on("click", function() {
    var visibleObj = $('.mainSection div:visible');
    if ($("div.panel2").css("display") == "none") {
      var inVisibleObj = $("div.panel2")
    }
    else {
      var inVisibleObj = $("div.panel1")
    }
    visibleObj.fadeOut(500, function() {
      inVisibleObj.fadeIn(500);
    })
  });
  
  
  $("button.panel3").on("click", function() {
    var visibleObj = $('.mainSection div:visible');
    if ($("div.panel3").css("display") == "none") {
      var inVisibleObj = $("div.panel3")
    }
    else {
      var inVisibleObj = $("div.panel1")
    }
    visibleObj.fadeOut(500, function() {
      inVisibleObj.fadeIn(500);
    })
  });
});
div.app {
  margin:50px auto;
  width: 400px;
  height: 400px;
  border-radius:10px;
  overflow: hidden;
  position: relative;
}
div.app > .blur {
  width: 100%;
  height: 100%;
  background: url(http://goo.gl/0VTd9W);
  -webkit-filter: blur(5px);
}
div.mainSection, div.dashboard{
  position: absolute;
  left: 0px;
  text-align:center;
  color:#fff;
  font-size:20px;
}
div.mainSection{
  width:100%;
  height:85%;
  background:rgba(0,0,0,0.5);
  top:0;
}
div.dashboard{
  width:100%;
  height:15%;
  background:rgba(255,0,0,0.5);
  bottom:0;
}
div.mainSection > .panel1,
div.mainSection > .panel2,
div.mainSection > .panel3 {
  width: 100%;
  Height: 100%;
  Background: rgba(0, 0, 0, 0.5);
  position: absolute;
  left: 0px;
  top: 0px;
}
div.mainSection > .panel3 > p{
  margin-top:80px;
}

.grid-button {
  background: none;
  border: none;
  padding: 3px;
  width: 100%;
}

.grid {
  display: inline-block;
  height: 4px;
  position: relative;
  width: 32px;
  transition: all 0.3s ease-in-out;
}
.grid:after, .grid:before {
  content: '';
  position: absolute;
  background-color: #FFF;
  display: inline-block;
  height: 4px;
  left: 0;
  width: 32px;
  transition: all 0.3s ease-in-out;
}

.grid.open {
  background-color: #FFF;
}
.grid.open:after {
  top: 10px;
}
.grid.open:before {
  top: -10px;
}

.grid.close {
  background-color: transparent;
  transform: scale(0.9);
}
.grid.close:after, .grid.close:before {
  top: 0;
  transform-origin: 50% 50%;
}
.grid.close:before {
  transform: rotate(135deg);
}
.grid.close:after {
  transform: rotate(45deg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="app">
    <div class="blur"></div>
    <div class="mainSection">
        <div class="panel1">
          <div>panel1</div>
          <div>panel1</div>
          
        </div>
        <div class="panel2" style="display: none;">
          <div>panel2</div>
        </div>
        <div class="panel3" style="display: none;">
          <p>Panel3</p>
          <div>panel3</div>
          <div>panel3</div>
        </div>
    </div>
    <div class="dashboard">
        <button class="panel2">button1</button>
        <button class="panel3">button2</button>
    </div>
</div>

This setup currently hides inner divs within panels after switching between them. Is there a way to maintain visibility of inner divs when toggling between panels?

Answer №1

To resolve the issue, you should update your JavaScript code as shown below:

$(function () {
    $("button.panel2").on("click", function() {
        var visibleObj = $('.mainSection > div:visible');

        if ($("div.panel2").css("display") == "none") {
            var inVisibleObj = $("div.panel2")
        }
        else {
            var inVisibleObj = $("div.panel1")
        }
        visibleObj.fadeOut(500, function() {
            inVisibleObj.fadeIn(500);
        });
    });


    $("button.panel3").on("click", function() {
        var visibleObj = $('.mainSection > div:visible');
        if ($("div.panel3").css("display") == "none") {
            var inVisibleObj = $("div.panel3")
        }
        else {
            var inVisibleObj = $("div.panel1")
        }
        visibleObj.fadeOut(500, function() {
            inVisibleObj.fadeIn(500);
        })
    });
});

The issue lies in the selector $('.mainSection div:visible');. This selector includes child divs, causing them to be hidden when trying to display the correct panel. By using

$('.mainSection > div:visible');
, only direct child divs are selected.

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

"Even when hidden, an HTML Div element still occupies space on the

I encountered an issue with my tabbedPage setup. Even though I have hidden content, it still occupies space on the page. Here is the code snippet that I am using: let tabHeader = document.getElementsByClassName("tabbedpage-header")[0]; let tabIndicator = d ...

When transitioning from another page, the header will cover a portion of the section

I am facing a specific issue that I need help with. My goal is to have the navigation bar link to different sections of a single page when clicked. For example, clicking on "Contact" should take the user to the contact section, and then if they click on "A ...

The state remains unchanged when useState is invoked

I am currently designing a unique restaurant website template. As part of the project, I have implemented a modal box with two arrow buttons to navigate between pages. The issue I am facing is that the value of the pageNumber variable, tracked using useSta ...

Steps for retrieving error code from a JSON error message

The error message is displayed as follows: "{\"errorCode\":\"2029\",\"errorMessage\":\"Duplicate Entry\"}" How can I retrieve the errorCode from the above code using ...

Filling dropdown menus with data from a MySQL database

In my MySQL database, I have two tables - one for events and one for instances. The events table contains event names and details, while the instance table links events to a venue table and includes dates for each specific event instance. I am currently w ...

The Journey of React Components: How Child Components Embrace the State Props of the Past

My understanding of states and props in React seems to be off. I am working on a React, Redux based app. Situation: I have a global SVG component that grabs the viewport dimensions from the app in the componentDidMount method. The default props for the ...

Harnessing the power of JavaScript to dynamically extract data from JSON formats

My goal is to extract multiple strings from a JSON object and combine them into one large string. Initially, I thought it made sense to use a loop that would add each new string during each iteration. However, upon implementation, some unexpected errors ar ...

Using Angular 2 alongside Twitter Bootstrap

What is the recommended approach for integrating the Twitter Bootstrap library with Angular 2 framework? There are typically two main methods: Begin by structuring the HTML using Bootstrap containers and then embed Angular components within these contain ...

Calculate the total of the smallest values in three columns as they are updated in real-time

I'm facing an issue with dynamically adding the sum of the 3 lowest values entered in columns. The Total Cost Field is not displaying any value, and changing the type from number to text results in showing NaN. I've tried various approaches but h ...

Implementing the "or" operator in Mongoose: A guide

I have two schemas, one for projects and the other for users A user can create multiple projects The user schema is as follows: { Name: String, Pass: string, } Project schema : { ProjectName: String, members : [ {type: ObjectId, ref : ' ...

Complete the form and send it to two separate locations

I'm encountering an issue with submitting a form to a page on my domain and then automatically resubmitting it to a different domain. Even though the code below successfully changes the form action and removes the ID, it fails to resubmit. It seems l ...

"Vanishing Act: Google Maps Markers in React Mysteriously Disappear upon

Struggling with the react-google-maps module, particularly when it comes to markers and component re-rendering. Here's the issue: Initially load page with map and a few markers (all good) Click on a tab in the nav-bar -> page switches content in ...

Can you help me understand how to access data from a selected option?

Is there a way to ensure that selecting black from the dropdown will trigger the reading of the src attribute? What modifications are needed in this code? $('.select').click(function() { var lalala = $(this).val(); $("#gallery .imgsx"). ...

Discover the JSON key name of the main container by utilizing jQuery's .ajax() function

I've been pondering a seemingly straightforward question but have yet to find the right answer despite my extensive searching. The JSON objects I'm dealing with are structured like this: { "crs_20868": [ { "Thing": "foo", "St ...

Debug errors occur when binding to computed getters in Angular 2

Currently, I am integrating Angular 2 with lodash in my project. Within my model, I have Relations and a specific getter implemented as follows: get relationsPerType() { return _(this.Relations) .groupBy(p => p.Type) .toPairs() ...

Stopping the PanResponder in React Native temporarily: A guide

Here is the snippet to create an instance of the panResponder: constructor( props ) { super( props ); this.position = new Animated.ValueXY(); this.panResponder = PanResponder.create( { onStartShouldSetPanResponder: ( ) => true, ...

Is window.getComputedStyle not functioning as anticipated?

Here is a function I created to determine the width and height of a text: function size_calculation(word,fontSize) { const div = document.body.appendChild(document.createElement('div')); div.textContent = word; div.style.cssText = ` fo ...

The combination of min-width and min-height is ineffective on Internet Explorer

My current issue involves CSS for media min-height and min-width, which works perfectly on Chrome but not on IE11. Here's the code snippet in question: @media (min-width: 0) and (max-width: 992px) { @media (min-height: 0) and (max-height: 480px ...

What is the reason behind decorators needing to utilize apply(this) on a function?

I've been delving into the realm of JavaScript and exploring decorator code. One thing I've noticed is that when looking at decorator code like the example below, the input function always applies to 'this' even though it doesn't a ...

After the function has been executed, the default parameters will still be present. What should be done in this

When I set default parameters in a function and then call the function again without those parameters, they still remain. I want them to be reset on every function call. It seems like a simple issue, but as a beginner, I'm struggling to understand it ...