Toggling back and forth between two divs using a pair of buttons

I've been experimenting with switching between two divs using two buttons, but I can't seem to get it right. I've searched all over the internet, but nothing has worked for me so far. Can you please point out what I might be doing wrong? Also, is there a way to achieve this without using jQuery?

Below is the code snippet I am currently working with:

// Show only one panel at a time
jQuery(".flip").on("click", function(e) {
  var target = jQuery(this).attr("href");
  jQuery(target).slideToggle("fast");
  jQuery(".content").not(target).hide();
  e.preventDefault();
});
.button-wrapper {
  text-align: center;
}

.button-wrapper a {
  text-decoration: none;
  color: black;
  margin: 10px
}

.content h1 {
  text-align: center;
  margin-top: 2em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
  <div class="button-wrapper">
    <a class="flip top-button" href="#first-div" target="" data-toggle="">Div1</a>
    <a class="flip top-button" href="#second-div" target="" data-toggle="">Div2</a>
  </div>

  <div class="content" id="cont1">
    <h1>I'm the first DIV</h1>
  </div>
  <div class="content" id="cont2">
    <h1>I'm the second DIV</h1>
  </div>

If you'd like to see this in action, check out my Codepen page here:

https://codepen.io/Sarithan/pen/Wywmrx

Answer №1

Your code looks good, but there is an issue with the Id attribute in your HTML elements. You need to ensure that the Id of the div matches the href of the corresponding flip. The reason your code isn't functioning as expected is because the id values are mismatched between the flip and content elements.

// handle panel toggling
jQuery(".flip").on("click", function(e) {        
    var target = jQuery(this).attr("href");
    jQuery(target).slideToggle("fast");
    jQuery(".content").not(target).hide();
    e.preventDefault();
});
.button-wrapper{
  text-align: center;
}

.button-wrapper a{
  text-decoration: none;
  color: black;
  margin: 10px
}

.content h1{
  text-align: center;
  margin-top: 2em;
}

.top-button{
    background-color: #ffffff;
    border: 1px solid black;
    text-align: center;
    width: 50px;
    height: 5rem;
    margin: 3px;
    -webkit-border-radius: 12;
    -moz-border-radius: 12;
    border-radius: 4px;
} 

.top-button a{
    text-decoration: none;
    color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
  <div class="button-wrapper">
   <a class="flip top-button" href="#first-div" target="" data-toggle="">Div1</a>
   <a class="flip top-button" href="#second-div" target="" data-toggle="">Div2</a>
   </div>

  <div class="content" id="first-div">
       <h1>Im the first DIV</h1>
  </div>
   <div class="content" id="second-div" style="display:none">
       <h1>Im the second DIV</h1>
  </div>

Answer №2

To update the id of the .content element, simply set it to match the value of the href attribute within the .flip, excluding the #

Additionally, modify your javascript from using slideToggle to using show, enabling the div to remain visible after the initial click

// display only one panel at a time
jQuery(".flip").on("click", function(e) {
  var target = jQuery(this).attr("href");
  jQuery(target).show("fast");
  jQuery(".content").not(target).hide();
  e.preventDefault();
});
.button-wrapper {
  text-align: center;
}

.button-wrapper a {
  text-decoration: none;
  color: black;
  margin: 10px
}

.content h1 {
  text-align: center;
  margin-top: 2em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="wrapper">
  <div class="button-wrapper">
    <a class="flip top-button" href="#first-div" target="" data-toggle="">Div1</a>
    <a class="flip top-button" href="#second-div" target="" data-toggle="">Div2</a>
  </div>

  <div class="content" id="first-div">
    <h1>Im the first DIV</h1>
  </div>
  <div class="content" id="second-div">
    <h1>Im the second DIV</h1>
  </div>

Answer №3

Here's a suggestion to make your button functionality more dynamic: set the button's href attribute to match the id of the content it should display. By doing this, clicking the button will reveal the corresponding content. Use CSS to hide all content classes initially and trigger a click event in the JavaScript code to show the content on page load. All you need to do is switch between views by clicking the buttons.

$(".flip").on("click", function(e) {
    e.preventDefault();
    $(".content").hide();
    $($(this).attr("href")).show("fast");    
});
$("a[href='#first-div']").trigger('click');
.button-wrapper {
  text-align: center;
}

.button-wrapper a {
  text-decoration: none;
  color: black;
  margin: 10px
}

.content h1 {
  text-align: center;
  margin-top: 2em;
}
.content{
  display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
  <div class="button-wrapper">
   <a class="flip top-button" href="#first-div" target="" data-toggle="">Div1</a>
   <a class="flip top-button" href="#second-div" target="" data-toggle="">Div2</a>
   </div>

  <div class="content" id="first-div">
       <h1>Im the first DIV</h1>
  </div>
   <div class="content" id="second-div">
       <h1>Im the second DIV</h1>
  </div>

Answer №4

Upon reviewing the code, it appears that the issue is not with jQuery but rather with the HTML structure. The problem arises from attempting to hide a div based on its ID, but the IDs (cont1, cont2) provided in the href tags are different. They should be consistent for proper functionality.

// Ensure only one panel is shown at a time
jQuery(".flip").on("click", function(e) {
  var target = jQuery(this).attr("href");
  jQuery(target).slideToggle("fast");
  jQuery(".content").not(target).hide();
  e.preventDefault();
});

$('#first-div').hide();
$('#second-div').hide();
.button-wrapper {
  text-align: center;
}

.button-wrapper a {
  text-decoration: none;
  color: black;
  margin: 10px
}

.content h1 {
  text-align: center;
  margin-top: 2em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
  <div class="button-wrapper">
    <a class="flip top-button" href="#first-div" target="" data-toggle="">Div1</a>
    <a class="flip top-button" href="#second-div" target="" data-toggle="">Div2</a>
  </div>

  <div class="content" id="first-div">
    <h1>I am the first DIV</h1>
  </div>
  <div class="content" id="second-div">
    <h1>I am the second DIV</h1>
  </div>

Answer №5

Forget about jQuery, regular JavaScript works just fine!
I see no need for all the jQuery complexities in this scenario.

Here's a simple solution using plain JavaScript:

  • Added a class="height0" with some CSS styles,
  • Swapped your a buttons with span buttons to simplify things and avoid unnecessary styling or event handling tricks.

// Pure JavaScript implementation
var flips = document.querySelectorAll(".flip");
var contents = document.querySelectorAll(".content");
flips.forEach(function(flip) {
  flip.onclick = function() {
    // Hide all content sections
    contents.forEach(function(content) {
      content.classList.add('height0');
    })
    // Display only the selected one
    // (You can include a timeout if you want!)
    setTimeout(function() {
      var target = flip.getAttribute("target");
      document.querySelector(target).classList.remove('height0');
    }, 500);
  }
});
.button-wrapper {
  margin: 16px;
  text-align: center;
}

.content h1 {
  text-align: center;
  margin-top: 1em; /* <-- Adjusted here */
}

.top-button {
  width: 50px;
  height: 5rem;
  margin: 3px;
  border: 1px solid black;
  border-radius: 4px;
  background-color: #fff;
  padding: 8px 12px;
  text-align: center;
}


/* Additional styles */

.content {
  max-height: 240px; /* <-- Customize as needed */
  transition: max-height 0.5s ease;
  overflow: hidden;
  background: #eee;
  padding: 0 1em;
}

.height0 {
  max-height: 0;
}
<div class="wrapper">
  <div class="button-wrapper">
    <span class="flip top-button" target="#first-div">Div1</span>
    <span class="flip top-button" target="#second-div">Div2</span>
  </div>
  <div class="content" id="first-div">
    <h1>First DIV</h1>
    <p>Content of the first DIV</p>
  </div>
  <div class="content height0" id="second-div">
    <h1>Second DIV</h1>
    <p>Content of the second DIV</p>
  </div>
</div>

I hope this solution fits your needs!

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

Real-time updates for UI data in Next.js Firestore are not being reflected

I'm currently working on implementing real-time changes using nextjs and Firebase Firestore. However, I've noticed that I still need to refresh the page in order for the updates to be visible. const [getUsers, setUsers] = useState(""); const che ...

What is the method to retrieve the class name of an element when the div is created as '<div id 'one' class="element one"></div>'?

I have three elements named one, two, and three, declared as seen below: <div id =container> <div id 'one' class="element one"></div> <div id 'two' class="element two"></div> < ...

Splitting React Code - Loading additional component following initial page load

I've recently integrated Router-based code splitting (lazy loading) in my app. As far as I understand, with lazy loading, a user will only load a specific chunk of the complete bundle when visiting a page. Is there a way to instruct React to start lo ...

Utilizing Page Objects to select dropdown list items in JavaScript for Protractor testing

I'm struggling with a particular issue during my testing process. The task requires selecting an item from a list as part of a form to create a new user. However, the test does not select an item from the list even though Protractor does not report an ...

Dynamically Add Routes in ExpressJS During Runtime

I am interested in creating routes dynamically at runtime, but I'm not entirely sure how to do it. Currently, I have the following code snippet: var app = express(); function CreateRoute(route){ app.use(route, require('./routes/customchat.js&ap ...

Using PHP to query the database and render text and links in the menu

On my website, users currently choose an "event" from a dropdown menu that is populated from a database (Check out the code below). Once a user selects an event from the menu, I want to display text links or a second dropdown menu with the "locations" ass ...

Limit the character input in AngularJS/Ionic to a specific number

I have a text input field that needs to restrict the user from entering more than a specific number of characters. Let's say I only want the user to type 10 characters, and if they try to enter more, the text field should not accept it. It should stop ...

Troubleshooting issue with Highcharts 3D rendering after using setState()

When working on implementing a 3d pie chart in React using react highchart, I encountered an issue. Whenever I utilize this.setState() inside the lifecycle method componentDidMount(), the 3d chart shifts from its original position to the right diagonally. ...

React.js pagination - removing empty values from an array

I'm currently working on implementing pagination logic that automatically updates the page numbers when the last index is clicked. For example: 1 2 3 4 5 If a user clicks on the number 5, it should display: 2 3 4 5 6 and so forth... I have succe ...

Is there any other factor aside from the lack of a CSRF token in an AJAX request with Django that could lead to a 403 error?

The primary reason behind the django + ajax 403 error is usually the absence of a csrf token. However, in my scenario, the csrf token is present and a similar ajax function is working fine. I will also provide the backend view function that handles the res ...

problems with hovering over radio buttons in Internet Explorer 9

Encountering a curious issue in IE9: When hovering over my top level wrapper div, the first radio button seems to be triggered as though it's being hovered over. This means that even if the last radio input is selected, clicking anywhere within the wr ...

Troubleshooting the Compatibility Issue Between Wordpress Theme and SSL

My personal blog is functional when accessed via http, but encounters issues with loading CSS code when accessed via https. Any suggestions on how to resolve this? The SSL certification is through the Let's Encrypt program. Website: Broken Link: ...

Issue with the jQuery scrollTo plugin causing unstable scrolling behavior when trying to view certain content

Hello everyone in the Community! I am facing a challenging issue with my full-page vertically and horizontally scrolling website powered by the scrollTo plugin. Everything works smoothly, except for when using content like the Nivo Slider which causes so ...

Having trouble integrating jQuery into an Angular CLI project

I'm trying to incorporate jQuery into my angular project created with angular cli. I followed the instructions provided on this website: To begin, I installed jQuery by running: npm install --save jquery; Next, I added type definitions for jQ ...

Issue with filtering of values returned by functions

I've been working with Angular's currency filter and I've run into an issue. It doesn't seem to be filtering the data that is returned from a function. I have a feeling that I might be missing something, perhaps it has to do with how th ...

Surprising Results when Using getBoundingClientRect()

Check out this code on CodePen In my current project, I'm attempting to position the footer div at the bottom of the page in such a way that it aligns with the maximum value of the bottom coordinates of both the menu and content divs (Math.max(menu, ...

What is the best way to display or conceal an array object using a toggle switch?

I'm trying to implement a show/hide functionality for descriptions when toggling the switch. Additionally, I want the switch to be initially checked and only show the description of each respective result. However, my current code is displaying all de ...

Troubleshooting a jQuery issue involving socket.io

I recently created a chat room using socket.io and jQuery. Inexperienced with node.js, I uploaded the files to an old FTP to get it online. Upon loading the website, I encountered an error in the console: Uncaught ReferenceError: io is not defined at ...

Angular toolbar on the left side that hovers seamlessly

1 I am using Angular Material toolbar and trying to position a span inside the toolbar on the left side. I have attempted using CSS float left, but it is not working. Can anyone provide some assistance please? <mat-toolbar> <span>le ...

Blazor Server: Seamless breadcrumb navigation updates with JavaScript on all pages

I have implemented a breadcrumb feature in my Blazor Server project within the AppLayout that functions for all pages: <ul id="breadcrumbs" class="breadcrumbs"> <li><a href="#">Home</a></li> ...