Press buttons to control the visibility of a <div> element

My issue involves managing 3 div elements and 3 buttons. Each button is responsible for opening a specific div, but when one div is opened, the others must be closed. While I was able to achieve this with some JavaScript code, my coding skills are minimal.

Each button is assigned a class: .button-1, .button-2, and .button-3. The divs are distinguished by different IDs: #div-1, #div-2, and #div-3.

Here is the code snippet I am currently using (repeated for each button and div):

jQuery(document).ready(function() {
// Hide the div
jQuery('#div-1').hide();
jQuery('.button-1').click(function(e){
e.preventDefault();jQuery("#div-1").slideToggle('opened closed');

});
});

jQuery(function($){
$('.button-1').click(function(e){
e.preventDefault();
$('#div-2').hide();
$('#div-3').hide();

});
});

While the code works well for opening and closing the same div smoothly, transitioning between different divs with open/close effects isn't as smooth.

Do you have any suggestions?
You can check out an example on jsFiddle.

I'm wondering if it's possible to prevent users from closing the .divs once one of them has been opened.

Thank you in advance!

Answer №1

If you want to smoothly transition between divs, a great approach is utilizing the fade method. By absolutely positioning them inside a wrapper, they will fade in and out seamlessly without affecting the layout of other elements on the page. Additionally, you can simplify your jQuery script for better efficiency. Check out an example on this website. To prevent the div from disappearing if the user clicks on the same button for an already open div, change all instances of fadeToggle() to fadeIn().

Javascript:

$(document).ready(function() {
  // Hide all divs initially
  $('#div-alex').hide();
  $('#div-exel').hide();
  $('#div-py').hide();
  
  // Swap functionality for each button click
  $('.boton-alex').click(function(e) {
    e.preventDefault();
    $("#div-alex").fadeToggle();
    $('#div-exel, #div-py').fadeOut();
  });
  $('.boton-exel').click(function(e) {
    e.preventDefault();
    $("#div-exel").fadeToggle();
    $('#div-alex, #div-py').fadeOut();
  });
  $('.boton-py').click(function(e) {
    e.preventDefault();
    $("#div-py").fadeToggle();
    $('#div-alex, #div-exel').fadeOut();
  });
});

HTML:

<div>
  <div>
    <a href="" class="boton-alex">
      Want a Big Party!
    </a>
  </div>
  <div>
    <a href="" class="boton-exel">
      Love to Party
    </a>
  </div>
  <div>
    <a href="" class="boton-py">
      Tight Budget
    </a>
  </div>
</div>
<div id="wrapper">
  <div id="div-alex" class="swap">
    <div class="central alex">
      <h2>Alex Muñoz</h2>
      <h3>“For us, the party is vital and important. We have a good budget reserved for it.”</h3>
      <p>As the founder of Exel Events, Alex Muñoz has vast experience with weddings. A sound and lighting technician by training, he sees each wedding as a unique work of art. He’s looking forward to meeting you!</p>
    </div>
  </div>
  <div id="div-exel" class="swap">
    <div class="central exel">
      <h2>Exel DJs</h2>
      <h3>“I place great importance on my wedding party and have set aside a budget for this part of the celebration.”</h3>
      <p>Exel DJs are your top choice: animated DJs who will take over the dance floor if the party starts to wane. Plus, you’ll get experienced DJs whom you can meet at the time of booking, even if your wedding is more than a year away. You can also choose from various lighting packages for the event.</p>
    </div>
  </div>
  <div id="div-py" class="swap">
    <div class="central ys">
      <h2>Play Yourself</h2>
      <h3>“I have a very limited budget and don’t mind providing a playlist or using rented equipment.”</h3>
      <p>Play Yourself is your best solution; you can rent it without a DJ or opt for a traditional non-animated DJ.</p>
    </div>
  </div>
</div>

CSS:

#wrapper {
  position: relative;
}
.swap {
  position: absolute;
  top: 0;
  width: 100%;
}
.swap>div {
  width: 60%;
  margin: 0 auto;
}

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

Generating a list of values separated by commas from a Microsoft Excel column after applying regular expressions

I have an Excel column that I need to convert into CSV format. A JavaScript regex has been provided to apply on the column values: var regex = new RegExp("[^a-z0-9',.]+","gi"); return input.replace(regex, "_").replace(/_+/g, "_").replace(/^_|_$|^&bso ...

What is the best way to extract specific values from a JSON array of objects using JavaScript?

I am facing some challenges in displaying values from the AJAX objects. My goal is to populate a select box with names using AJAX, but I seem to have made an error somewhere in my code. Can someone please assist me in identifying and correcting the mistake ...

Stop the Bootstrap 5 accordion from expanding when the spacebar is pressed in the header text input

Within my React app using react-bootstrap, I have implemented an accordion component that expands or collapses based on the user's interaction with a text input located in the AccordianHeader component. Interestingly, whenever the spacebar is released ...

Does ColdFusion 2016 have the ability to convert special characters?

Upon conducting research and working with CF 2016, I encountered an issue. When using JQuery/Ajax to submit form data, entering a semi-colon ; in one of the text areas converts the symbol to &#59. The reason for this conversion to HTML code is unclear ...

Determine if the data in an HTML table should be spanned when it

I'm facing a scenario where my HTML table contains duplicate data in a particular column, as illustrated below I am looking to automatically merge the cells of rows in the HTML table if the data in them is identical, similar to the table displayed be ...

Using bootstrap with a navbar in an asp.net mvc application proves to be challenging

There are only a few bootstraps that work with this site, such as the default and lumen bootstrap. You can find them on However, other bootstraps like materia and flatly seem to be causing display issues. Here's an example of how it looks: Edit: Bel ...

Initiate monitoring for child component modifications

I'm looking to disable 'changeDetection' for the parent component while enabling it for the child component. Can you provide an example of how this can be achieved? The parent component contains static data, meaning change detection is not ...

What are the steps involved in manipulating templates following manual $compile?

Currently, I am working on a web application using AngularJS and need to display a list of categories. Each category within the list may contain an array of subcategories. To achieve this, I have developed a recursive directive called category that funct ...

How can you store JavaScript objects to files, including their methods, in a Node.js environment?

In reading about saving objects to files in Node.js here on Stack Overflow, I understand the process. However, I am curious if there is a method that allows for writing an object in a manner that would enable me to reload the object into memory along wit ...

Save this page for later by using JavaScript to create a

Does anyone have a solution as to why window.location.href does not save the current webpage URL as a bookmark? Thank you ...

Is there a way to customize the color of a React component from a different source?

I am currently utilizing a React component library called vertical-timeline-component-react. <Fragment> <Timeline> <Content> <ContentYear startMonth="12" monthType="t ...

Utilizing Web Worker to Load Textures in Three.js

When a large texture image is applied to a Mesh in Three.js for a substantial amount of time, it causes the browser's main thread to freeze. Consider the following scenario: var texLoader = new THREE.TextureLoader(); texLoader.load('someLargeTe ...

Initiate an animation as you scroll down

How can I create an animation that transitions from color to grayscale, triggered only when the user scrolls down? This is necessary because my website contains numerous images that require scrolling to reach. Check out the fiddle example here: http://jsf ...

Deselecting options using jQuery

Currently, I am facing a challenge with jQuery in deselecting a select option element. Let me explain my situation: I have 3 select options: [ Select 1 ] [ Select 2 ] [ Select 3 ] Situation: Initially, Select 1 is populated with data retrieved from ...

Sending a POST request to a Flask server using Stripe and AJAX

I am attempting to implement a function that triggers an ajax request when a stripe form is submitted. However, using the .submit() method doesn't seem to be working as expected. Here is my current code: HTML <form action="/download_data" method= ...

The width of a <div> element in CSS is not dependent on the width

Is there a way to make tables within a div have relative widths to each other? For example, if one table has a large image or long word causing it to extend to 100%, how can we ensure that the other tables in the same div also adjust to 100% width? CSS . ...

Why won't angularjs interpret my object accurately?

Currently, I am in the process of developing an angularjs application and I have encountered a minor issue. The problem arises when I populate a list of projects and then apply filtering based on certain conditions. Visually, everything appears fine on the ...

The stored information causes the material ui text fields to malfunction

Having trouble with my text fields in a React and Material UI application. When autofill data is saved, the styling breaks. The component code is included below. I've searched online but couldn't find any helpful solutions. import React, { useSta ...

Share an image using only the publish_actions authorization

There are some apps I've come across that only request access to users_photos and publish_actions (not publish_stream or photo_upload). Surprisingly, they are able to upload photos without being approved for User Generated Photos (e.g. Instagram). Wh ...

What could be causing the lack of data with 'react-hook-form'?

I have encountered an issue while working with react-native and using 'react-hook-forms' for creating dynamic forms. The problem is that the data object returned is empty, even though it should contain the values entered in the input fields. When ...