Is it possible to create a single button that, upon clicking, fades in one image while simultaneously fading out another?

My goal is to have the blue square fade in on the first button click, then fade out while the red square fades in on the second click.

Unfortunately, it seems that my current code is not achieving this effect. I'm open to any suggestions or help on how to correct this issue.

var currentscene = 0;

function next() {
  currentscene++;
  if (currentscene === 1) {
    var element = document.getElementById("blue");
    element.classList.add("fade-in");
  }
  if (currentscene === 2) {
    var elementBlue = document.getElementById("blue");
    elementBlue.classList.remove("fade-in");
    elementBlue.classList.add("fade-out");

    var elementRed = document.getElementById("red");
    elementRed.classList.add("fade-in");
  }
}
.squareblue {
  height: 50px;
  width: 50px;
  top: 50px;
  background-color: blue;
  position: absolute;
  opacity: 0;
  animation-fill-mode: forwards;
}

.squarered {
  height: 50px;
  width: 50px;
  top: 100px;
  background-color: red;
  position: absolute;
  opacity: 0;
  animation-fill-mode: forwards;
}

.fade-out {
  animation: fadeOut ease 2s
}

@keyframes fadeOut {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}

.fade-in {
  animation: fadeIn ease 2s
}

@keyframes fadeIn {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}
<div id="blue" class="squareblue"></div>
<div id="red" class="squarered"></div>

<button class="button" onclick="next()">next</button>

Answer №1

There are a couple of errors and areas for improvement in your code.

In your if conditions, you were assigning the value of 1 and 2 to the variable currentscene instead of using the comparison operator ==. I introduced the remainder operator to allow the loop to continue indefinitely.

To optimize performance, I defined the elements at the beginning rather than retrieving them from the DOM on each iteration.

Instead of utilizing a CSS keyframes animation, I opted for the CSS transition property to achieve opacity changes smoothly.

If you have any questions, feel free to ask! 🚀

let currentscene = 0;
const blue = document.getElementById("blue");
const red = document.getElementById("red");

function next() {
  currentscene++;
  if (currentscene % 2 == 0) {
    blue.classList.remove("opaque");
    red.classList.add("opaque");
  }
  else if (currentscene % 2 == 1) {
    red.classList.remove("opaque");
    blue.classList.add("opaque");
  }
}
.squareblue,
.squarered {
  height: 50px;
  width: 50px;
  position: absolute;
  opacity: 0;
  animation-fill-mode: forwards;
  transition: 1s;
}

.squareblue {
  top: 50px;
  background-color: blue;
}

.squarered {
  top: 100px;
  background-color: red;
}

.opaque {
  opacity: 1;
}

button {user-select: none}
<div id="blue" class="squareblue"></div>
<div id="red" class="squarered"></div>

<button class="button" onclick="next()">Next</button>

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

Designing a fixed bottom footer enclosed within a wrapper that expands from the top header to the bottom footer

I have created the basic structure of my webpage using HTML / CSS. However, I now realize that I need a sticky footer that remains at the bottom of the screen with a fixed position. Additionally, I want the main content area, known as the "wrapper," to str ...

Gather every hyperlink and input fields without utilizing jQuery

Is there a way to target all a and form elements without relying on jQuery? My end goal is to achieve the following functionality: document.querySelectorAll('a').forEach(element => { element.addEventListener('click', () => { ...

Error: The requested collection# cannot be found in the Node.js Express routing system

Recently, I have started learning nodejs and implemented a simple API that allows users to log in with passport and then redirects them to the /collections route. While this part is functioning correctly, I am encountering issues with POST requests which a ...

Angular 2 ngIf displaying briefly before disappearing

Encountering a strange issue with an Angular 2 ngIf statement where it appears on the page for a brief moment and then disappears. The content is visible, but it doesn't remain on the page. I suspect it might be related to some asynchronous behavior. ...

Designing a user interface that consists of numerous distinct components

Challenge I'm faced with a dilemma regarding site A, which is built using React. Specifically, I need to find a way to integrate smaller React components into site A whenever a user navigates to a specific page within the site. Each of these smalle ...

When transitioning an iOS Swift app to the background, a NodeJS error arises: 'Headers cannot be set after they have been sent to the client'

My app is built using Swift/SwiftUI. I utilize the ObservableObject and JSONDecoder to retrieve data from my Node.JS Express API and display it within the app: struct DevicesList: Decodable { var data: [DeviceInfo] } struct DeviceInfo: Decodable { ...

"Adding a new and unique document to Meteor's MongoDB collection

Currently, I have a simple Tags Collection in Meteor where I check for duplicate Tag documents before inserting: var existingTag = Tags.findOne({name: "userInput"}) If the existingTag is undefined, then I proceed with the insertion. However, I am wonderi ...

The annoying Facebook "add a comment" popup refuses to close

Occasionally, the "add a comment" popup (iframe) in Facebook's Like plug-in fails to close and obstructs access to the content underneath. This issue has been noted while using Chrome 21 and Firefox 15. To replicate this problem, you can visit the fo ...

Integrate a PHP form that includes a redirect feature and an optional opt-in box

I'm a beginner and I'm trying to enhance this code by adding some extra features. When the form is submitted, I want the page to redirect to an external URL like www.google.com The checkbox should be automatically checked and when the client re ...

What could be causing my slider to malfunction?

No errors are being returned by the console. Currently utilizing Unslider. The setup includes: <div class="slider"> <ul> <li><img src="img/one.jpg" alt=""></li> <li><img src="img/one.jpg" ...

Updating a model within an ng-repeat directive from external sources

Within my controller, there is a repeater where each item has its own unique status: <div ng-controller="..."> <div ng-repeat"...">{{status}}</div> </div> Currently, changing the status within the repeater by using status = &apo ...

Using react-hook-form to easily update form data

While working on my project with react-hook-form for updating and creating details, I encountered a problem specifically in the update form. The values were not updating properly as expected. The issue seems to be within the file countryupdate.tsx. import ...

Struggling to synchronize animation timing between elements using jquery

When you navigate to an album (for example, Nature because I'm still working on the others) and select one of the images, they all gradually fade out while the selected image appears on the screen. What's actually happening is that the selected i ...

Storing information within a Express application using Postgres

Recently, I've been delving into the world of Express and experimenting with a program that allows users to create events and invite others. While I know about using join tables to retrieve data, I'm curious if there's a way to organize the ...

Resolving Issues in HTML and the Dynamic Duo of PHP and MySQL

Hey there, I've been a reader for a while now but this is my first time posting. I'm really into PHP and I've been working on a page lately. Right now, I've got the DB connection set up nicely and my SELECT statement is doing exactly wh ...

My goal is to develop a table that is both able to be resized and easily repositioned

I've been working on a project to develop an interactive table that can be manipulated, resized, and repositioned within a canvas. The code snippet below shows my attempt at creating this table on the canvas: var canvas = document.getElementById("dra ...

Tips for maintaining an open ng-multiselect-dropdown at all times

https://www.npmjs.com/package/ng-multiselect-dropdown I have integrated the ng multiselect dropdown in my Angular project and I am facing an issue where I want to keep it always open. I attempted using the defaultOpen option but it closes automatically. ...

Tips on avoiding the collapse of the right div when positioned under a left float in a full page layout

Trying out a full page layout for the first time, with a left div serving as a block style nav. #admin_nav { width: 230px; height: 100%; background-color: #f9f9f9; border-right: 1px solid #ddd; float: left; } The content is on the rig ...

Creating a type definition for the createSelector function based on the useQuery result

Struggling to find the correct typings for the createSelector res parameter from redux-js, especially in TypeScript where there are no examples or explanations available. The only guidance is provided in JS. const selectFacts = React.useMemo(() => { ...

Is it possible to obtain the index of a table row using querySelector?

Is it possible to find the rowIndex of the first occurrence of a table row within the #myTable using JavaScript? http://jsfiddle.net/bobbyrne01/fmj6np6m/1/ html .. <table id="otherTable"></table> <table id="myTable"></table> js ...