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

Displaying Multiple HighCharts on a single AngularJS page

As a beginner with HighCharts, I am working on adding two Highcharts to the same page that will access the same data source but display different pieces of data for each graph. For example, the categories will remain constant while the series[] will vary. ...

Editable content <div>: Cursor position begins prior to the placeholder

Having an issue with a contenteditable div where the placeholder text starts behind the cursor instead of at the cursor position. Any suggestions on how to correct this? <div id="input_box" contenteditable="true" autofocus="autofocus" autocomplete="o ...

Setting custom parameters ($npm_config_) for npm scripts on Windows allows for more flexibility and customization in

I'm struggling with passing custom parameters from the command line to npm scripts in my package.json file. Despite researching on various platforms, including Stack Overflow, I haven't found a solution that works for me. Here's what I' ...

Place the divs over the background image by using relative positioning

I am working on a project where I have a full-width div with a background image containing people. I want to display a tooltip when hovering over each person, but I am facing challenges in aligning the divs properly. Image maps with % widths do not seem t ...

Retrieve the contents of the browser's DOM from within an Android operating system runtime

Imagine a typical login page similar to the one depicted below: https://i.stack.imgur.com/SF1Bd.jpg To interact with the HTML elements within the DOM, we can utilize either jQuery or conventional JavaScript like so: https://i.stack.imgur.com/e5aQZ.png ...

Creating and accessing a temporary binary file using Node Js

Challenge I have been working on integrating the Google Text To Speech (TTS) service to save a generated binary audio file to Google Cloud Storage (GCS). Considering that saving a local binary file in Firebase's Cloud Functions environment may not b ...

Click on an element that is nested within another element that can also be clicked on

I'm facing a challenge while attempting to create an accordion inside another accordion. The issue arises with the nested elements and their behavior upon clicking. Essentially, I have a parent div with the class .applicant, which expands on click by ...

Transform the JSON response into a map

I have a functioning code that I am looking to adjust. let table_specs = {'columns': [ {'name': 'Col1', 'width': 7, ....}, {'name': 'Col2', 'width': 8, . ...

Execute the component function located within one page using another page

Can someone help me understand how to trigger OnSwipe from inside a different JS file named CardFooter.js? This file contains a button with an OnClick event that triggers OnSwipe from the preceding JS file called CardItem.js. Both of these files are includ ...

Generating JSON data from a dropdown menu element

I'm working on a web page that showcases information for students in my database. One key field is their birth country, currently stored as the full name of the country. My goal is to convert these full country names into two-character strings. For ex ...

I am having trouble with node.js express not recognizing the path to my CSS files

My objective is to load information onto an HTML page using Node.js and Express. The issue I am facing is that when I try to open the main page (which displays all the books from the database), everything works smoothly - the CSS and JS files are located ...

There seems to be an issue with accessing the requested page,

Having some trouble with routing in external files and getting a 'Cannot Get /' error. Can anyone help me figure out what I'm doing wrong? Here is my server.js file: const express = require('express'); const mongoose = require(&a ...

Turn off bodyparser when uploading files in Node.js

This query is quite similar to another one on Stack Overflow regarding how to disable Express BodyParser for file uploads in Node.js. The solution provided there was for Express3, but when tested with the updated Express 4, it didn't work as expected. ...

"Using the selected option from a dropdown list to pass to a PHP file for autocomplete functionality

Although there is no error in the code, I am facing an issue where, after selecting an option from the brands dropdown, when I type in the product field, it passes "%" instead of the brand id (1, 2, or 3). Is there a way to modify the code so that it passe ...

Disabling the loading of JavaScript on a Magento website

Seeking advice - I'm experiencing a delay on my website due to 3 unnecessary javascripts that are being loaded. Is there a way to prevent these scripts from loading or being searched for? Listed below is the website log where I am unable to locate jq ...

The PhpStorm/JavaScript expression statement doesn't involve assignment or function call

I am striving to enhance the cleanliness of my method. Based on the value of an integer number, I am generating different date formats, resulting in the following: getRanges() { var currentDate = new Date(); //This can ...

I am struggling to style a form effectively with CSS grid

I am working on setting up a 2-column HTML form using CSS grid. In the first column, I have labels placed on individual rows. In the second column, I have form elements also placed on individual rows. This is my initial attempt at this task and I am sti ...

What steps should I take to resolve the issue of my endpoint failing to accept POST requests?

I am in the process of developing a customized API, with an endpoint that is specified as shown below: https://i.stack.imgur.com/sZTI8.png To handle the functionality for this endpoint, I have set up a Profiling Controller. Inside my controller directory ...

The use of Handlebars expressions within the {{#each}} block is crucial

I am currently working on my new portfolio site and I have a question about how to place handlebars expressions inside an #each loop. The project is an express application generated by express-generator, and I am using the express-handlebars NPM package: ...

How can I retrieve the second letter in Materialize CSS FormSelect by using the keyboard?

On my website that utilizes materializeCSS and Jquery, I have encountered an issue with a select box containing numerous options. Typically, when using a select box, I can press a letter multiple times to cycle through options starting with that letter. ...