Effortlessly switch between multiple divs with jQuery

I am working on a functionality where multiple divs should be displayed or hidden based on the button clicked. Initially, all buttons and divs are visible. Upon clicking a button, only the corresponding div should be visible. Subsequent clicks on other buttons should toggle the visibility of their respective divs as well. I am considering using cookies or local storage to achieve this feature, as my current code only allows me to deactivate the divs with the first click.

$(function() {
    $('.button').click(function(){
        $(this).toggleClass('inactive');
        $('#mydiv'+$(this).attr('target')).toggle();
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div>
  <button class="button" target="1">Button 1</button>
  <button class="button" target="2">Button 2</button>
  <button class="button" target="3">Button 3</button>
</div>

<div id="mydiv1">
  <p>Div 1</p>
</div>

<div id="mydiv2">
  <p>Div 2</p>
</div>

<div id="mydiv3">
  <p>Div 3</p>
</div>

Answer №1

To toggle only the button/div that was clicked, you must first reset the previous state of all elements to their initial state (remove the "inactive" class and show all divs), and then toggle the state.

$(function() {
    $('input[type="checkbox"]').change(function() {
      let checked = $('input[type="checkbox"]:checked');
      $('.inactive').removeClass('inactive');
      
      if (checked.length == 0) {
        $('.subdiv').show();
        
        return;
      }
      
      $('input[type="checkbox"]:not(:checked)').closest('label').addClass('inactive');

      $('.subdiv').hide();
      
      checked.each(function () {
        $('#mydiv' + $(this).val()).toggle();
      });
    });
});
.inactive {
  color: red;
}

label input {
  display: none;
}

label {
  border: 1px solid gray;
  border-radius: 3px;
  padding: 2px 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div>
  <label><input type="checkbox" value="1"/>Button 1</label>
  <label><input type="checkbox" value="2"/>Button 2</label>
  <label><input type="checkbox" value="3"/>Button 3</label>
</div>

<div id="mydiv1" class="subdiv">
  <p>Div 1</p>
</div>

<div id="mydiv2" class="subdiv">
  <p>Div 2</p>
</div>

<div id="mydiv3" class="subdiv">
  <p>Div 3</p>
</div>

Answer №2

To achieve the desired effect, start by hiding all the divs and revealing the correct one when the corresponding button is clicked.

$(function() {
  $('.button').click(function() {
    $(this).toggleClass('active');
    $('#mydiv' + $(this).attr('target')).toggle();
  });
});
/*
  Ensure all divs with IDs starting with "mydiv" are hidden
*/

div[id^="mydiv"] {
  display: none;
}

.active {
  background-color: green;
  color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div>
  <button class="button" target="1">Button 1</button>
  <button class="button" target="2">Button 2</button>
  <button class="button" target="3">Button 3</button>
</div>

<div id="mydiv1">
  <p>Div 1</p>
</div>

<div id="mydiv2">
  <p>Div 2</p>
</div>

<div id="mydiv3">
  <p>Div 3</p>
</div>

Answer №3

Is it necessary to utilize a toggle function, or is there an alternative solution available?

$(function() {
  $('.button').click(function() {
  $('.inactive').removeClass('inactive');
    $(this).toggleClass('active');
    $('.subdiv').show();
 
    $('.mydiv' + $(this).attr('target')).toggle();
  });
});
/*
  Hide all divs that have an id starting with "mydiv"
*/

.active {
  background-color: green;
  color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div>
  <button class="button" target="1">Button 1</button>
  <button class="button" target="2">Button 2</button>
  <button class="button" target="3">Button 3</button>
</div>

<div class="mydiv1" hidden>
  <p>Div 1</p>
</div>

<div class="mydiv2" hidden>
  <p>Div 2</p>
</div>

<div class="mydiv3" hidden>
  <p>Div 3</p>
</div>

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

What is the best way to include query parameters in form data within a Rails link_to instead of tacking them onto the URL?

I am facing an issue with my page that displays transaction search results. I have a search filter based on the "Token" column and when clicked, the search criteria should be set, and the search params should be passed as form-data in a POST method. Howeve ...

An example of text that includes a link using ES6 template strings

My goal is to display the message "I read and agree to the privacy policy.privacy policy." where the 'privacy policy' part is a clickable link. I attempted the following code but it resulted in "I read and agree to the [object object]." const p ...

The async function in Jasmine is causing issues with expectedAsync functionality

Currently conducting the following examination: it("should receive rejection", async done => { class someTest { async run(){ return this.rejectFunc(); } async rejectFunc(){ return new Promise( ...

Executing window.open from Html.Actionlink in ASP.NET MVC 4

Here is the code block I am working with: @foreach (System.Data.DataRow drEquipment in Model.EquipmentList.Rows) { <tr> <td valign="top">@drEquipment["ColumnName"]<br /></td> <td valign="to ...

webstorm error: unresolved function or method when using npm azure-storage modules

Encountering a problem with WebStorm IDE when using azure-storage library as it is unable to find the correct methods for intelligent coding (although the code runs without errors). View image of unresolved function or method Appreciate any help you can ...

Transferring canvas element via socket with JS stack size limit

I'm encountering an issue where I need to transfer a canvas element over sockets using socket.io and Node.js. The code snippet below illustrates my approach: var myCanvas = document.getElementById("myCanvas"); var ctx = myCanvas.getContext("2d"); // ...

I am currently in the process of conducting an automated test focused on the creation of a new Facebook account

I am currently facing a challenge while attempting an automated test on Facebook. The issue lies in clicking the "Create Account" button using FindElement by id, which is not functioning as expected. public void createAccount(String firstName, String lastN ...

Using Angular and Jade to pass an array from a controller to script tags

I am trying to figure out how to access an array in my controller and display it accurately within the <script> tags in my jade template. For instance: Controller.js $scope.myArray = ["item1","item2"]; Within my index.jade: script. var clien ...

Toggle a Vue.js method to display responses for a particular question

Currently, I am in the process of developing a simple toggle feature for a FAQ section. The idea is that when a user clicks on an icon associated with a specific question, only that question's answer should be displayed. Although the function is oper ...

Increase the div id using jQuery

I've got this code snippet here and, oh boy, am I a newbie. How can I increase the number in the div using a jQuery script? if($res >= 1){ $i=1; while($row = mysqli_fetch_array($qry)){ echo "<div clas ...

Concealing or revealing an image with jQuery when hovering

I currently have 3 <a> tags within my html, each containing 2 images. Specifically, the greyscale images are the ones that are visible while the colored ones are set to display:none. I am aiming to achieve a functionality where upon hovering over th ...

`Take action on a row by selecting the Edit option in CodeIgniter`

In my table, I have data displayed with an edit button in each row. What I want is for a pop-up or lightbox to appear when the edit button is clicked, without refreshing the page, and display all fields within that box. I am familiar with updating in the c ...

The damping effect in three.js OrbitControls only activates when the mouse is pressed, however there is no damping effect once the

I find it difficult to articulate: Currently, I am utilizing OrbitControls in three.js and have activated damping for a smoother rotation with the mouse. It is somewhat effective but not entirely seamless. When I click and drag, the damping feature works ...

implementing conditional logic in angularjs expressions

<p>{{isExisted}}</p> Looking to show either "Active" or "Inactive", but the isExisted variable only returns true or false. Need help with setting up a conditional if else statement to change it to the desired value. ...

The Material UI month picker interface is not displaying correctly

When trying to implement the code snippet below, <MonthPicker/> I am encountering issues with the UI of the month picker both on the website and at times. https://i.stack.imgur.com/EKsYA.png It seems like the month picker is being utilized in a di ...

developing a sleek visual transition using CSS animation

Have you seen the awesome animation on Discord's website? Check it out here! The way those coins move up and down so smoothly is really impressive. How can I recreate that effect for my own images? I decided to start with this code snippet img { ...

Guiding users who have disabled JavaScript through redirection

When faced with the following markup, users whose browser has JavaScript disabled will be redirected to an alternative page. This alternate page may attempt to mimic the site's functionality without JavaScript or simply display a warning message infor ...

Using Paper.js to access and manipulate document.body.style.opacity within a paperscript

My website is essentially one large canvas image. Currently, the body fades in when loaded using this code: <body onLoad="document.body.style.opacity='1'"> However, I want to initiate this fade within my paperscript because sometimes the ...

leveraging JQuery plugins alongside Grails resources plugin

How can I easily integrate a JQuery plugin like FancyBox into a Grails application using the resources plugin? The FancyBox plugin comes with .js, .css, and image files. It assumes that the image and .css files are located in the same directory. In some ...

The RC-dock library's 'DockLayout' is not compatible with JSX components. The instance type 'DockLayout' is not a valid JSX element and cannot be used as such

Despite encountering similar questions, none of the provided answers seem to address the issue within my codebase. My project utilizes React 17, Mui v5, and TS v4. I attempted to integrate a basic component from an external package called rc-dock. I simply ...