Incorporate a smooth transition effect to a dynamically resizing div button

In my current setup, I have 3 buttons that can toggle between different visible divs. In the future, I may add more buttons to switch between additional divs.

At the moment, the first div is active (display set to block), while all other divs are hidden (display set to none).

When a button is clicked, the active div changes based on the button that was clicked.

function switchUnit1() {
            if (document.getElementById('units2')) {
                if (document.getElementById('units2').style.display == 'block') {
                    document.getElementById('units2').style.display = 'none';
                    document.getElementById('units1').style.display = 'block';
                }
            }
            if (document.getElementById('units3')) {
                if (document.getElementById('units3').style.display == 'block') {
                    document.getElementById('units3').style.display = 'none';
                    document.getElementById('units1').style.display = 'block';
                }
            }
            if (document.getElementById('units4')) {
                if (document.getElementById('units4').style.display == 'block') {
                    document.getElementById('units4').style.display = 'none';
                    document.getElementById('units1').style.display = 'block';
                }
            }
}  
  
function switchUnit2() {
            if (document.getElementById('units1')) {

                if (document.getElementById('units1').style.display == 'block') {
                    document.getElementById('units1').style.display = 'none';
                    document.getElementById('units2').style.display = 'block';
                }
            }
            if (document.getElementById('units3')) {
                if (document.getElementById('units3').style.display == 'block') {
                    document.getElementById('units3').style.display = 'none';
                    document.getElementById('units2').style.display = 'block';
                }
            }
            if (document.getElementById('units4')) {
                if (document.getElementById('units4').style.display == 'block') {
                    document.getElementById('units4').style.display = 'none';
                    document.getElementById('units2').style.display = 'block';
                }
            }
}
  
function switchUnit3() {
            if (document.getElementById('units1')) {

                if (document.getElementById('units1').style.display == 'block') {
                    document.getElementById('units1').style.display = 'none';
                    document.getElementById('units3').style.display = 'block';
                }
            }
            if (document.getElementById('units2')) {
                if (document.getElementById('units2').style.display == 'block') {
                    document.getElementById('units2').style.display = 'none';
                    document.getElementById('units3').style.display = 'block';
                }
            }
            if (document.getElementById('units4')) {
                if (document.getElementById('units4').style.display == 'block') {
                    document.getElementById('units4').style.display = 'none';
                    document.getElementById('units3').style.display = 'block';
                }
            }
}
<div class='units-buttons' id='units-buttons'>
      <button class='units-button units-selected' onclick='switchUnit1();' type='button' value='Click'>Type 36A</button>
      <button class='units-button' onclick='switchUnit2();' type='button' value='Click'>Type 36B</button>
      <button class='units-button' onclick='switchUnit3();' type='button' value='Click'>Type 56</button>

<div id='units1' style='display: block;'>Image 1</div>
<div id='units2' style='display: none;'>Image 2</div>
<div id='units3' style='display: none;'>Image 3</div>

I am looking to incorporate a fading transition effect when switching from one div to another each time a button is clicked.

Answer №1

To create a fade in/out animation, experiment with using `opacity`, `z-index`, and `transition` properties.

Applying the CSS rule `position: absolute;top: 0;` to the elements with the class `.units` ensures they are positioned correctly.

const btn = [...document.getElementsByClassName("units-button")];
const units = [...document.getElementsByClassName("units")];
const fading = (e) => {
  let i = btn.indexOf(e.target);
  [btn, units].forEach((arr) => arr.forEach((d) => d.classList.remove("units-selected")));
  [btn, units].forEach((arr) => arr[i].classList.add("units-selected"));
};
btn.forEach((d) => d.addEventListener("click", fading));
.units {
  opacity: 0;
  z-index: 0;
  transition: 0.4s;
  position: absolute;
  top: 0;
}

.units.units-selected {
  opacity: 1;
  z-index: 1;
  position: relative;
}
<div class="units-buttons" id="units-buttons">
  <button class="units-button units-selected" type="button" value="Click">Type 36A</button>
  <button class="units-button" type="button" value="Click">Type 36B</button>
  <button class="units-button" type="button" value="Click">Type 56</button>
</div>
<div style="position: relative;">
  <div class="units units-selected">Image 1</div>
  <div class="units">Image 2</div>
  <div class="units">Image 3</div>
</div>

Answer №2

To achieve the desired effect, it would be necessary to utilize a different method other than changing the display property, as transition does not support display.

Instead, for a smooth fade-in effect, you can use opacity and transition its value. It is also advisable to toggle classes on the divs rather than directly setting styles.

Below is an enhanced version of your code for better scalability and readability:

const units = [];
initUnits();

function initUnits() {
  units.push(document.getElementById('units1'));
  units.push(document.getElementById('units2'));
  units.push(document.getElementById('units3'));
}

function switchUnit(index) {
  if (index >= 0 && units.length > index) {
    for (let i = 0; i < units.length; i++) {
      units[i].classList.add("hidden");
      if (i === index) {
        units[i].classList.remove("hidden");
      }
    }
  }
}
.can-hide {
  transition: opacity 1s;
  opacity: 1;
}

.hidden {
  opacity: 0;
}
<div class='units-buttons' id='units-buttons'>
  <button class='units-button units-selected' onclick='switchUnit(0);' type='button' value='Click'>Type 36A</button>
  <button class='units-button' onclick='switchUnit(1);' type='button' value='Click'>Type 36B</button>
  <button class='units-button' onclick='switchUnit(2);' type='button' value='Click'>Type 56</button>

  <div id='units1' class="can-hide">Image 1</div>
  <div id='units2' class="can-hide hidden">Image 2</div>
  <div id='units3' class="can-hide hidden">Image 3</div>
</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

Adjusting the width of a DIV element within a table cell

In my ASP.NET application, I am facing an issue with table column widths not rendering as expected in the browser. Despite setting the column width to 100px, it appears as either 96px or 108px. The problem seems to be related to having a div inside the th ...

Having trouble fetching JSON data from an Express server?

I successfully set up my first basic server using express, however I am encountering an issue when trying to fetch JSON data from a file called data.json: Here is the code for the server: const express = require('express') const app = express() ...

Utilizing jQuery for seamless communication between parent and child iFrame windows

On my webpage, there is an iFrame containing a table where I want to add a click event to the rows. The challenge is retrieving the selected row within the iFrame from the parent window. The goal is to define a class for a clicked table row like this: $( ...

Adjust the width and height of the span to encompass more than just the content within it

I'm struggling to apply height and width to empty spans using CSS, but the span only fills its content <div class="container"> <div id="widgets-container"> <span class="widget" name="widget1" style="background-col ...

Is there a way for me to retrieve the widths of all child elements within an HTML document?

I have been working on a JavaScript (jQuery) function to calculate the maximum width of all child and children's-child elements within a specific div element. Here is the code I have written so far: function setBodyMinWidth(name){ var max = 0; $(nam ...

transmit FormData containing two files and a text message to the controller

I have encountered an issue while trying to send a FormData object containing text fields, an image file, and a PDF file to an action in the controller. Despite my efforts, the form data is not being sent to the action. I have checked for errors through br ...

Changing navigation position while scrolling to a different anchor using fullpage.js

Currently, I have a lengthy scrolling webpage that utilizes fullpage.js. The navigation is fixed in position over the page and each active slide is highlighted by its corresponding link. My goal is to have the link move to the top position when it's ...

Achieve sliding animations with Pure CSS using slideUp and slideDown techniques

Currently, I have implemented a code snippet to showcase a menu along with displaying submenus upon hovering over the main menus. Now, I am looking to introduce some animation effects for the submenus when they appear, similar to the slideUp and slideDown ...

Struggling to make images wrap properly using flexbox

I've been struggling to get these images to wrap properly within my container. They keep overflowing beyond the designated width and I'm not sure if it's because I have paragraphs placed under each image. Any ideas on how to make 3 images ap ...

Bring in SASS variables to enhance Material UI theme in NextJS

Within my project, I currently have the following two files: materialTheme.ts import { createMuiTheme, Theme } from "@material-ui/core/styles"; const theme: Theme = createMuiTheme({ palette: { primary: { main: "#209dd2", contras ...

Bug in Chrome (Win) causing middle-mouse-button overflow issue

Take a look at this demo: http://jsfiddle.net/pixelfreak/AN5Wb/ Everything works perfectly until attempting to scroll using the middle mouse button. At that point, you can see beyond the boundaries of the element. This issue does not occur in Firefox or ...

Leveraging mongo aggregate functionality within the meteor framework to calculate the total number of unlocked and locked

So, I have a collection where I store documents related to users with a structure like: {_id: "hofjew233332j4", userId: "fhewojfw34324", achievementUnlocked: true }; My goal is to use the aggregate and underscore functions to group the documents by user ...

Sending a Single Input Field value to a Controller in Laravel using JQuery

Looking to submit a single form value using jQuery to a database in Laravel. Below is the input field: <input type="text" id="comment"> <button id="cmntSubmit" type="button">Post</button> Check out the jQuery code I am using: $(docum ...

Determine in AngularJS whether there is a checked checkbox in a table row

Here is my HTML code snippet: <tbody ng-repeat="notification in notifications"> <tr> <td rowspan="{{notification.specs.length+1}}">{{notification.notification_id}}</td> </tr> <tr ng-repeat="position in ...

Substitute the functions within a Node.js module with simulated functions

I am currently working on a Node.js project that serves as an API wrapper. To ensure the reliability of my code, I am writing unit tests using nodeunit and need to incorporate mock functions into the module. For instance, I require a function that mimics s ...

TypeError occurs when app.use is used with multer configuration

I am currently facing an issue while attempting to set up multer in my app.js file (using node.js/express) for enabling users to upload images. The code snippet in app.js is as follows: // Various require statements including passport, cookie parser, etc. ...

Utilizing arrays to populate a line graph in Highcharts

I am struggling to figure out how to incorporate data from an array obtained from another function in my javascript file into my line graph. I want to confirm that this is feasible without switching to a different graphing package. Below is my current co ...

What is the best way to customize the styles of a reusable component in Angular2?

I am working with a reusable component called "two-column-layout-wrapper" that has its styles defined in the main .css file. In another module, I need to use this component but customize the width of two classes. How can I override these styles? import ...

Placing a moveable object in a designated spot for dropping at the desired location

I've been attempting to clone and drop a draggable object at the exact position within a droppable area where the drop event takes place. While I have come across examples online that demonstrate appending draggables to droppables, they all tend to re ...

Internet Explorer 11 Ajax problem

Once again, Internet Explorer is causing some issues. I have a file called validation.php where the values from a text box are sent for validation. The text box value is read and then a result indicates whether it is valid or not. This functionality work ...