Tips for creating seamless image transitions using a toggle button

My transition effect is working smoothly, but I am having trouble setting it up for the image. How can I resolve this issue?

I attempted the following:

var lightsOff = document.querySelector("#lights-off");
var lightsOn = document.querySelector("#lights-on");
lightsOff.style.display = "block";
lightsOn.style.display = "none";

And also this:

var lightsOff = document.querySelector("#lights-off");
var lightsOn = document.querySelector("#lights-on");
lightsOff.style.display = "none";
lightsOn.style.display = "block";

Below is the complete code:

function myFunction() {
  var elements = document.querySelectorAll(".one, .three, .five");
  elements.forEach(function(element) {
    element.classList.toggle("dark-mode");
    if (element.classList.contains("dark-mode")) {
      if (element.classList.contains("one")) {
        var logoElement = element.querySelector('.logo');
        var h2Element = element.querySelector('h2');
        var sloganElement = element.querySelector('.slogan');
        logoElement.style.setProperty('color', 'white');
        sloganElement.style.setProperty('color', 'white');
        h2Element.style.setProperty('color', 'white');
      } else if (element.classList.contains("three")) {
        var textThreeOne = element.querySelector('.text-threeone');
        var textThreeTwo = element.querySelector('.text-threetwo');
        var p = element.querySelector('.text-threetwo + p');
        textThreeOne.style.setProperty('color', 'white');
        textThreeTwo.style.setProperty('color', 'white');
        p.style.setProperty('color', 'white');

        var lightsOff = document.querySelector("#lights-off");
        var lightsOn = document.querySelector("#lights-on");
        lightsOff.style.display = "block";
        lightsOn.style.display = "none";

        var blackmoon = document.querySelector(".moon");
        blackmoon.style.display = "block";
      } else if (element.classList.contains("five")) {
        var inputs = element.querySelectorAll('input');
        var textarea = element.querySelector('textarea');
        var submitBtn = element.querySelector('input[type="submit"]');
        inputs.forEach(input => {
          input.style.setProperty('background-color', '#1f1f1f');
          input.style.setProperty('color', '#ffffff');
        });
        textarea.style.setProperty('background-color', '#1f1f1f');
        textarea.style.setProperty('color', '#ffffff');
        submitBtn.style.setProperty('background-color', '#1f1f1f');
        // Add mouseover color
        submitBtn.style.setProperty('transition', 'background-color 0.2s');
        submitBtn.addEventListener("mouseover", function() {
          submitBtn.style.setProperty('background-color', '#101010');
        });
        submitBtn.addEventListener("mouseout", function() {
          submitBtn.style.setProperty('background-color', '#1f1f1f');
        });
        var contact = element.querySelector('#contact');
        var pOne = element.querySelector('.five>p+p');
        var pTwo = element.querySelector('.five>p+p+p');
        contact.style.setProperty('color', 'white');
        pOne.style.setProperty('color', 'white');
        pTwo.style.setProperty('color', 'white');
      } else {
        element.style.setProperty('color', 'white');
      }
    } else {
      if (element.classList.contains("one")) {
        var logoElement = element.querySelector('.logo');
        logoElement.style.setProperty('color', '#353535');
        var sloganElement = element.querySelector('.slogan');
        sloganElement.style.setProperty('color', '#353535');
        var sloganElement = element.querySelector('h2');
        sloganElement.style.setProperty('color', '#353535');

        var blackmoon = document.querySelector(".moon");
        blackmoon.style.display = "none";
      } else if (element.classList.contains("three")) {
        var textThreeOne = element.querySelector('.text-threeone');
        var textThreeTwo = element.querySelector('.text-threetwo');
        var p = element.querySelector('.text-threetwo + p');
        var lightsOff = document.querySelector("#lights-off");
        var lightsOn = document.querySelector("#lights-on");
        lightsOff.style.display = "none";
        lightsOn.style.display = "block";

        p.style.setProperty('color', '#353535');
        textThreeOne.style.setProperty('color', '#353535');
        textThreeTwo.style.setProperty('color', '#353535');
      } else if (element.classList.contains("five")) {
        var inputs = element.querySelectorAll('input');
        var textarea = element.querySelector('textarea');
        var submitBtn = element.querySelector('input[type="submit"]');
        inputs.forEach(input => {
          input.style.setProperty('background-color', '#efefef');
          input.style.setProperty('color', 'black');

        });
        textarea.style.setProperty('background-color', '#efefef');
        textarea.style.setProperty('color', 'black');

        submitBtn.style.setProperty('background-color', '#437bff');
        submitBtn.style.setProperty('color', 'white');

        // Add mouseover color
        submitBtn.style.setProperty('transition', 'background-color 0.2s');
        submitBtn.addEventListener("mouseover", function() {
          submitBtn.style.setProperty('background-color', '#133edb');
        });
        submitBtn.addEventListener("mouseout", function() {
          submitBtn.style.setProperty('background-color', '#437bff');
        });

        var contact = element.querySelector('#contact');
        var pOne = element.querySelector('.five>p+p');
        var pTwo = element.querySelector('.five>p+p+p');
        contact.style.setProperty('color', '#353535');
        pOne.style.setProperty('color', '#353535');
        pTwo.style.setProperty('color', '#353535');
      }
    }
  });
}
.one,
.three,
.five {
  transition: 1500ms;
}
<div>
  <button class="darkmodebtn" onclick="myFunction()"></button>
  <img id="lights-off" src="../images/darkmode.png" style="display: none;">
  <img id="lights-on" src="../images/ABC.png">
</div>

Answer №1

document.querySelector('.light-on1').addEventListener('click', function() {
  const el = document.querySelector('.container1 img');
  toggle_light_on_display(el);
})
document.querySelector('.light-off1').addEventListener('click', function() {
  const el = document.querySelector('.container1 img');
  toggle_light_off_display(el);
})

function toggle_light_on_display(el) {
  el.style.opacity = '0';
  el.style.display = 'block';
  const to = setTimeout(function() {
    el.style.opacity = '1';
    clearTimeout(to); // It's better to clear the timeout when no longer needed
  }, 200) // This slight delay is for the display block to finish
}

function toggle_light_off_display(el) {
  el.style.opacity = '0';
  const to = setTimeout(function() {
    el.style.display = 'none';
    clearTimeout(to); // It's better to clear the timeout when no longer needed
  }, 500) // This delay represents the transition delay
}

document.querySelector('.light-on2').addEventListener('click', function() {
  const el = document.querySelector('.container2 img');
  toggle_light_on_visibility(el);
})
document.querySelector('.light-off2').addEventListener('click', function() {
  const el = document.querySelector('.container2 img');
  toggle_light_off_visibility(el);
})

function toggle_light_on_visibility(el) {
  el.style.opacity = '0';
  el.style.visibility = 'visible';
  const to = setTimeout(function() {
    el.style.opacity = '1';
    clearTimeout(to); // It's better to clear the timeout when no longer needed
  }, 200) // This slight delay is for the visibility visible effect to finish
}

function toggle_light_off_visibility(el) {
  el.style.opacity = '0';
  const to = setTimeout(function() {
    el.style.visibility = 'hidden';
    clearTimeout(to); // It's better to clear the timeout when no longer needed
  }, 500) // This delay represents the transition delay
}
.container1 img {
  display: none;
  transition: 500ms ease-in all;
}

.container2 img {
  visibility: hidden;
  transition: 500ms ease-in all;
}
<button class="light-on1">light-on display</button>
<button class="light-off1">light-off display</button>
<div class="container1">
  <img src="https://picsum.photos/id/20/800/600" alt="">
</div>

<button class="light-on2">light-on visibility</button>
<button class="light-off2">light-off visibility</button>
<div class="container2">
  <img src="https://picsum.photos/id/30/800/600" alt="">
</div>

Here are two versions, one using display and the other using visibility.

To observe the difference in usage, place the container 2 block and buttons 2 before those of container 1 in your HTML code. The visibility method helps preserve space on the page.

In the provided code, I separated the on and off functions, but they can be combined into a single toggle function. Detection can be based on style opacity or visibility.

You can adjust the delays as you see fit. Note that a small delay should be included when transitioning from display to on or from visibility to visible, as browsers need time to render these changes.

You can also experiment with the image transitions and their timing. If you alter the transition duration, remember to adjust the off delay accordingly.

This code can be easily adapted to suit your needs and integrated into your projects.

Answer №2

Here is a new snippet where I have combined the two functions into one using your HTML structure:

function myFunction() {
  const lightsOff = document.querySelector("#lights-off");
  const lightsOn = document.querySelector("#lights-on");
  if (lightsOff.style.display === 'none') {
    toggle_light_display('off');
  } else {
    toggle_light_display('on');
  }
}

function toggle_light_display(test) {
  let el1, el2;
  if (test === 'off') {
    el1 = document.querySelector("#lights-on");
    el2 = document.querySelector("#lights-off");
  } else {
    el1 = document.querySelector("#lights-off");
    el2 = document.querySelector("#lights-on");
  }
  el1.style.opacity = '0';
  let to = setTimeout(function() {
    el1.style.display = 'none';
    clearTimeout(to);
    el2.style.opacity = '0';
    el2.style.display = 'block';
    to = setTimeout(function() {
      el2.style.opacity = '1';
      clearTimeout(to);
    }, 200)
  }, 500)
}
img {
  transition: 500ms ease-in all;
}
<div>
  <button class="darkmodebtn" onclick="myFunction()">switch</button>
</div>
<div>
  <img id="lights-off" src="https://picsum.photos/id/20/800/600" alt="" style="display: none;">
  <img id="lights-on" src="https://picsum.photos/id/30/800/600" alt="">
</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

Step by step guide on integrating ReactJS into your current node.js backend application

I am currently working on a basic node.js API Setup: | project-name | public | index.html | ... some static js/css | app.js | package.json app.js var express = require('express'), bodyParser = require('body-parser'), ...

Creating dynamic styles with Material-UI's useStyles

Attempting to implement the same logic using material-ui's useStyle feature <div className={'container ' + (state.unlocked ? 'containerUnlocked' : '')}> I thought it might look like this: <div className={`${clas ...

The dropdown menu disappears when I hover over the tab, making it impossible for me to navigate it in the react app

My navigation component includes a Games tab with a dropdown menu that appears when you hover over it. However, I'm facing an issue where the dropdown menu closes before the user can transition from hovering over the games tab to the actual dropdown m ...

Optimal approach for integrating enum with Angular, Mongoose, and Node.js

When it comes to fetching values from MongoDB and displaying them with AngularJS, the process can be straightforward with Jade but becomes more complex with Angular. Here is how the data flows: An array of items is retrieved from MongoDB, each containin ...

The npm module parsing has encountered an error... It appears that a suitable loader is required to process this file format

Recently, I made changes to an open-source code that was working perfectly until yesterday. I can't seem to figure out what went wrong as I didn't make any significant changes. Despite searching on Stack Overflow for a similar issue, my lack of k ...

Show a notification when utilizing AJAX requests

I consist of two separate files: one written in PHP and the other one in JavaScript and HTML. PHP file : <?php session_start(); //start session $_SESSION['data'] = "The content should be displayed as alert in the JS file"; JS/HTML File: & ...

Select multiple items from a list in HTML using the power of jQuery with a Multi Select

I'm facing an issue with the multi-select box. I attempted to choose multiple values using jQuery, but only the last one seems to be selected. Can someone assist me, please? Below is my code: <script> $(function(){ <?php foreach ($selectd ...

Tips for keeping the scroll position of a bootstrap table when reloading the page

Displayed below is a bootstrap table with specific features. <div class="row"> <table id="question-selection" class="table table-sm table-hover table-wrapper"> <tbody> {% for placer in chapter_questions %} ...

Finding a solution to this issue in Angular will consistently result in a false outcome

Can anyone explain why I keep getting the error message "This condition will always return 'false' since the types 'typeof ChartType' and 'ChartType' have no overlap" whenever I try to compare charTypeEnum with ChartType.text? ...

Reload the text content of a locally hosted webpage within an iframe at regular intervals

I have set up a simple webpage on my local machine to showcase the contents of some text files on a dedicated monitor. However, I am facing an issue where refreshing the entire webpage causes flickering. My goal is to only refresh the iframes and reload t ...

stop the menu component from triggering a re-render

I am facing an issue where the menu opens and closes briefly when I refresh the page. I want to find a way to prevent this re-rendering process. Every time I refresh, my console.log shows: false 'open' navigation.jsx:23 item navigation.jsx: ...

The issue of a false value not being correctly matched in Jasmine is causing problems

Currently, I am utilizing the following code to evaluate an element with aria-checked="false". expect((accessPolicyPage.listSelectAll).getAttribute("aria-checked")).toEqual("false"); The output is presenting as Expected [ 'false' ] to equal &ap ...

A guide on retrieving the selected option from a dropdown menu with React Material UI

Utilizing Material UI React, I am constructing a dropdown menu containing various options. My concern is: if I choose two options from different dropdowns within the menu, how can I intercept or store which option was selected? Below is a snippet of my co ...

What is the method for accessing an image in JavaScript?

Currently, I am developing a currency converter for a gaming marketplace and I would like the users to be able to generate images using JavaScript. While most of the work is completed, I am facing an issue where the images are not displaying properly and i ...

Stop the Bootstrap row from automatically adjusting to the height of the tallest child column element, and instead utilize the extra space below the smaller element

My current framework is Bootstrap 5.2. I am aiming to create two columns, each with a col-md-6 class inside a row. You can visualize the layout through this image: . The challenge I'm facing is the inability to add another row with col-md-6 element ...

Utilizing Vue.js for Tabs in Laravel 5.8

I am encountering an issue in Laravel while attempting to set up a Vue instance for tabs. Currently, only Tab 1 and Tab 2 are displayed without any content, and the tabs themselves are not clickable links. Could this problem be related to how I am calling ...

Javascript's associative arrays: a versatile tool for data organization

Is there a way to achieve the same functionality in JavaScript as this PHP code?: $this->gridColumnData[] = array('field' => 'id', 'width' => 50, 'title' => 'Enquiry Id') ; $this->gridColumn ...

The Nuxt auth module fails to update the user's loggedin status within the store state

Currently, I am implementing Authentication functionality using the Nuxt Auth Module. My frontend is built on Nuxt Js, while my backend is running Laravel 5.7 In nuxt.config.js, I have configured the auth settings as follows: auth: { strategies: { ...

Is there a way to restrict the amount of user input that is allowed?

Is it possible to restrict the input quantity when using the built-in arrow icon in the text field, but not when typing manually? <TextField variant="outlined" label="Quantity" onChange={(e) => setItemName({...i ...

What is the best way to switch between List and Grid view while automatically updating the image displayed?

**#Unique Component Implementation** import React from 'react'; import Typography from '@material-ui/core/Typography'; import Grid from '@material-ui/core/Grid'; import { makeStyles } from &apo ...