Hide all div elements except one by toggling them at the same position

Iā€™m diving into the world of jQuery and facing some challenges with the .toggle() function.

My goal is to have multiple <div> elements displayed in the same position, but only one visible at a time. When a new <div> is opened, the previous one should automatically close. Here's my current HTML setup:

$(document).ready(function() {
  $("#button1").click(function() {
    $("#box1").toggle(1000);
  });
});
$(document).ready(function() {
  $("#button2").click(function() {
    $("#box2").toggle(1000);
  });
});
.container {
  width: 90px;
}

.box1 {
  background-color: green;
  color: red;
  display: none;
}

.box2 {
  background-color: blue;
  color: yellow;
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class=box1 id=box1>
    This is Box 1
  </div>

  <div class=box2 id=box2>
    This is Box 2
  </div>
</div>

<a href="#" id="button1">Box1</a>
<a href="#" id="button2">Box2</a>

Furthermore, I believe that using just one toggle() function instead of four would be more efficient for what I want to achieve. However, attempting to apply the same function across different IDs or classes isn't working as expected. What am I overlooking or doing incorrectly in this scenario?

Answer ā„–1

Typically, you can utilize a single document ready function.

To simplify, you could implement a single click function to manage your toggles. As you are utilizing trigger links, it is important to have a way to identify the target box. Adding an additional attribute like target-box with the ID of the desired box would allow you to achieve this effectively.

The addition of the same box class to both div elements eliminates the need for individual box1/box2 classes since differentiators are already handled by their respective IDs.

Including a toggle class to the links simplifies the selector and removes redundant 'open/close' duplicates, as the toggle class is designed to handle both actions seamlessly.

jQuery(document).ready(function($){
  $('.toggle').on('click', function(){
    var targetBox = $(this).attr('target-box'); // Locate the target box
    
    $('.box').not(targetBox).hide(1000); // Conceal all other boxes
    
    $(targetBox).toggle(1000); // Toggle the visibility of the current box
  });
});
.container {
  width: 90px;
}

.box1 {
  background-color: green;
  color: red;
  display: none;
}

.box2 {
  background-color: blue;
  color: yellow;
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="box box1" id="box1">
    This is Box 1
  </div>

  <div class="box box2" id="box2">
    This is Box 2
  </div>
</div>

<a href="#" class="toggle" target-box="#box1">Toggle Box1</a>
<a href="#" class="toggle" target-box="#box2">Toggle Box2</a>

Answer ā„–2

If you're looking for a solution, this method might work well for your needs. By targeting elements with a specific marker, such as a class, you can easily hide or show them as required. In the code snippet below, I've assigned the class "box" to all box elements. When opening a box, all other boxes are hidden first before displaying the selected one.

With this setup, clicking open will reveal the chosen box while closing any others. Similarly, clicking close will only shut the specified box.

$(document).ready(function() {
  $("#button1").click(function() {
    $(".box").hide(1000);
    $("#box1").show(1000);
  });
  $("#buttonclose").click(function() {
    $("#box1").hide(1000);
  });
  $("#button2").click(function() {
    $(".box").hide(1000);
    $("#box2").show(1000);
  });
  $("#buttonclose2").click(function() {
    $("#box2").hide(1000);
  });
});
.container {
  width: 90px;
}

.box1 {
  background-color: green;
  color: red;
  display: none;
}

.box2 {
  background-color: blue;
  color: yellow;
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="box box1" id=box1>
    This is Box 1
  </div>

  <div class="box box2" id=box2>
    This is Box 2
  </div>
</div>

<a href="#" id="buttonclose">Close Box1</a>
<a href="#" id="buttonclose2">Close Box2</a>

<a href="#" id="button1">Open Box1</a>
<a href="#" id="button2">Open Box2</a>

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

Avoiding Page Reloads with Ajax while Removing Entries from a Table in Laravel

I am encountering an issue where I can click the button, but it requires a refresh to execute the delete action. Is there something in my ajax code causing this problem and why is it refreshing? I want the button to instantly delete without the need for a ...

What is the best way to empty the input field after a download event is completed in Node.JS?

For hours on end, I've been struggling with a persistent issue in my video downloader app. After successfully downloading a video, the input field where the URL is entered remains filled instead of clearing out. The screenshot below illustrates the p ...

The Vue template is not able to recognize the Pug language syntax within the .vue file

According to the Vue documentation: Template processing differs from other webpack loaders, as pug-loader and similar template loaders return a function instead of compiled HTML. Instead of using pug-loader, opting for original pug is recommended. Test ...

Encountering issues with styling the search bar using CSS and unable to see any changes reflected

I am currently working on creating a searchBar and customizing its CSS, but unfortunately, most of the styling properties seem to not be taking effect. So far, only changing colors seems to work as expected. .mainBar{ background-color: blue; width: ...

Ways to switch up the titles on UploadThing

Recently, I started working with the UploadThing library and encountered a situation where I needed to personalize some names within the code. Here is what I have so far: Below is the snippet of code that I am currently using: "use client"; imp ...

Guide on populating a textbox with values through Ajax or Jquery

Consider the scenario where there are three textboxes. The first textbox requires an ID or number (which serves as the primary key in a table). Upon entering the ID, the semester and branch fields should be automatically filled using that ID. All three fie ...

The vital role of Package.json in the distribution of packaged products

I am currently uncertain about the purpose of package.json in relation to packaging. My understanding is that dependencies listed under dependencies will be included in the distribution package, while those under devDependencies will not be included. How ...

The reason why I am unable to utilize ng-click within jQueryDialog remains unclear

I am looking to develop a dynamic div using jQuery and AngularJS that can change its background on the fly. My goal is to have the ability to open a JQuery UI Dialog window by clicking on the text within the background, allowing me to choose a new backgro ...

How to achieve the wrapping functionality in ReactJS that is similar to

Is there a ReactJS equivalent to jQuery's wrap method? I want to wrap menuContents with the following element: <ul className="nav nav-pills nav-stacked"></ul> The contents of menuContents are generated like this: let menuContents = thi ...

Steps for generating an HTML form in a fresh window

I am currently working with this function: // open a new window. Create and submit form function createSubmitForm(response) { var external = window.open('about:blank', 'external'); var doc = external.document; var body = $( ...

React-bootstrap's Modal is glitching and only partially appearing on the screen

I am a beginner in frontend development and I've been struggling to position the modal at the center of the screen; it keeps appearing on the right side. I am currently using "bootstrap/dist/css/bootstrap.min.css" for my CSS. Should I create a new CSS ...

Is it possible to blend javascript with server-side javascript code in a single project?

At the moment, I find myself in a peculiar situation where I need to combine JavaScript with server-side code. Here's how it looks: function PerformGlobalCallback(sender, value) { var index = hfCurrentTabIndex.Get("activeIndex")); wi ...

How to place a button in the bottom center of a panel using asp.net

After learning about centering a button at the bottom-center inside a div, it became clear that it's similar to centering a button within a panel. I managed to achieve this by adding the following CSS to the button: position:absolute; margin-left ...

Using JavaScript, pass an array containing a list of JSON values

I am attempting to store a list of JSON Objects in an array using JavaScript. Below is the list: [{"_id":1,"json":{"age":10,"name":"carlos"}},{"_id":2,"json":{"age":10,"name":"carlos"}}] Here is the code snippet I have written: var arrayResults = ' ...

What are the advantages of storing data in HTML tags that do not contain any content?

Is it considered poor practice to include an empty span in a template, or is there a more effective solution available? Is it acceptable to use a blank span tag like this within my code? <span class="stored-id-number" data-idnumber="1234"><!-- em ...

Utilizing onClick to target data within a .map function

I am struggling with the code provided below: const test = (e) => { console.log('example:', e.target.item.attributes.dataIWant); } {records.map((item, index) => { return ( <> <Accordion key={index} ...

Whiskey Angostura and Straight Row Set to 8, not 12

Recently, I incorporated Bourbon, Bitters, and Neat into my rails application. However, I am encountering an issue where the number of grid-columns is stuck at 8 instead of the desired 12. To address this problem, I have taken the following steps: Ensur ...

issue with mongoose virtual populate (unable to retrieve populated field)

During my project using mongoose with typescript, I encountered an issue with adding a virtual called subdomains to populate data from another collection. Although it worked without any errors, I found that I couldn't directly print the populated data ...

Initial space in model variable not being displayed

Hey there, I am working with a model variable called "name" that is linked to a span element like this: <input type="text" ng-model="name"> <span ng-bind="name"></span> My goal is to display the text entered in the input field without r ...

The webpack development server is failing to inject CSS

Upon reviewing the stdout output after executing the script that triggers webpack-dev-server, it seems like the scss | css files are being processed and emitted correctly. However, when visiting "localhost:8080" in devtools, the CSS is not injected by the ...