Guide on making a button display an image, then switch back to the initial image when clicked again

Currently, I have this neat feature on my website where there's a button that toggles the image/background color - kind of like a dark mode switch. The background change is working fine, but I'm encountering some challenges with organizing the images properly. Here's what I have in terms of code:

function myFunction() {
    var element = document.body;
    element.classList.toggle("dark-mode")
}

function changeImage() {
    var image = document.getElementById('myImage');
    if(image.src.match("https://drive.google.com/uc?export=view&id=1zv8IxOU6cHccEanlwTnFmx9HWNQR9AA4")) {
        image.src = "https://drive.google.com/uc?export=view&id=1H8ZfWPnLQ1dgKIo7geyyzlkAeh_QHrIa";
    } else {
        image.src = "https://drive.google.com/uc?export=view&id=1H8ZfWPnLQ1dgKIo7geyyzlkAeh_QHrIa";
    }
}
.title {
    font-size: 50px;
    text-align: center;
    background-color: #C1C1C1;
    border-radius: 20px;
    font-family: arial;
    color: #00486B;
}

.img {
    background: coral;
    width: 500px;
    padding: 30px;
    margin-left: auto;
    margin-right: auto;
    display: block;
}

.body {
    padding: 25px;
    background-color: white;
    color: black;
    font-size: 25px;
}

.dark-mode {
    background-color: black;
    color: white;
}

.dark-mode .title {
    color: yellow;
    background-color: navy;
}

.dark-mode .img {
    background-color: teal;
}

.main {
    text-align: center;
    font-size; 50px; border-radius: 20px;
    font-family: arial;
    color: #00486B;
}
<!doctype html>
<html>

<head>
    <title>Java</title>
</head>

<body class="main">
    <h1 class="title">TOGGLE DISPLAY</h1> <img src="https://drive.google.com/uc?export=view&id=1zv8IxOU6cHccEanlwTnFmx9HWNQR9AA4" class="img" id="myImage">
    <br>
    <button onclick="myFunction(); changeImage();" value="Change">CLICK</button>
</body>

</html>

Answer №1

Indeed, your code is functioning properly; however, the image loading speed may be slow due to pulling it from the drive. Consider changing the image source or utilizing CSS to toggle the display of the image (although this approach may seem a bit unconventional)

<html>

<head>
  <style>
    .title {
      font-size: 50px;
      text-align: center;
      background-color: #C1C1C1;
      border-radius: 20px;
      font-family: arial;
      color: #00486B;
    }

    .img {
      background: coral;
      width: 500px;
      padding: 30px;
      margin-left: auto;
      margin-right: auto;
      display: block;
    }

    .body {
      padding: 25px;
      background-color: white;
      color: black;
      font-size: 25px;
    }

    .dark-mode {
      background-color: black;
      color: white;
    }

    .dark-mode .title {
      color: yellow;
      background-color: navy;
    }

    .dark-mode .img {
      background-color: teal;
    }

    .main {
      text-align: center;
      font-size: 50px;
      border-radius: 20px;
      font-family: arial;
      color: #00486B;
    }

    #myImage2 {
      display: none;
    }
  </style>
  <script>

    function myFunction() {
      var element = document.body;
      element.classList.toggle("dark-mode")
    }

    function changeImage() {
      var image1 = document.getElementById('myImage1');
      var image2 = document.getElementById('myImage2');

      if (image1.style.display === "none") {
        image1.style.display = "block";
        image2.style.display = "none";
      } else {
        image1.style.display = "none";
        image2.style.display = "block";
      }
    }
  </script>
  <title>Java</title>
</head>

<body class="main">
  <h1 class="title">TOGGLE DISPLAY</h1>
  <img src="https://drive.google.com/uc?export=view&id=1zv8IxOU6cHccEanlwTnFmx9HWNQR9AA4" class="img" id="myImage1"><br>
  <img src="https://drive.google.com/uc?export=view&id=1H8ZfWPnLQ1dgKIo7geyyzlkAeh_QHrIa" class="img" id="myImage2"><br>
  <button onclick="myFunction(); changeImage();" value="Change">CLICK</button>
</body>

</html>

Answer №2

  • Avoid relying on the URL to determine your decision, as Google's answer may redirect you to a different URL. Instead, consider using
    document.body.classList.contains('dark-mode')
    .
  • Try assigning diverse values to if/else blocks.

Answer №3

Switching between images is a simple task by utilizing an array of image sources for easy reference and using the indexOf method to determine the current image source's position within the array.

const q=(e,n=document)=>n.querySelector(e);

/*
  The original images were too large and slow to load, so they have been replaced with adorable kittens for better clarity.
*/
const srcs=[
  'https://placekitten.com/452/450?image=2',
  'https://placekitten.com/452/450?image=1'
];

let oPromises=[];
srcs.forEach( src=>{
  oPromises.push(new Promise((resolve,reject)=>{
    let img=new Image();
        img.onload=function(e){
           resolve( this.src )
        }
        img.src=src;
  })
)});
Promise.all( oPromises )
  .then( values=>{
    q('button').addEventListener('click',function(e){
      document.body.classList.toggle("dark-mode");
      let img=q('img');
          img.src=values[ 1 - values.indexOf( img.src ) ];
    });
  })
  .catch(err=>console.warn(err))
.title {
  font-size: 50px;
  text-align: center;
  background-color: #C1C1C1;
  border-radius: 20px;
  font-family:arial;
  color: #00486B;
}
.img {
  background: coral;
  width: 500px;
  padding: 30px;
  margin-left: auto;
  margin-right: auto;
  display: block;
}
.body {
  padding: 25px;
  background-color: white;
  color: black;
  font-size: 25px;
}
.dark-mode {
  background-color: black;
  color: white;
}
.dark-mode .title{
  color:yellow; 
  background-color: navy;
}
.dark-mode .img{
  background-color: teal;
}
.main {
  text-align: center;
  font-size; 50px;
  border-radius: 20px;
  font-family: arial;
  color: #00486B;
}
<h1 class="title">TOGGLE DISPLAY</h1>
<img src="https://placekitten.com/452/450?image=1" class="img" />
<button>CLICK</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

Insert a JavaScript object into the rendered HTML using the componentDidMount lifecycle method

I'm trying to incorporate a JavaScript object into the template once the component has mounted for tracking purposes. Here is how I want the object to be rendered: var tracking = { pagename: 'page name', channel: 'lp&ap ...

Switch between Accordions/Tabs with JavaScript (ES6)

Encountering a minor issue with the accordion/tab layout provided in this link: https://jsfiddle.net/drj3m5tg/ The problem is that on mobile, the "+" icon remains as "-" when opening and closing tabs. Also, in desktop view, sometimes tabs need to be clic ...

Exploring how to access properties of objects in javascript

As a novice on this platform, I'm uncertain if the title may be deceiving, but I have a question regarding the following scenario: var someObject ={} someObject.info= { name: "value" }; How can I acce ...

Create various designs for a section of a webpage

My goal is to create a coding playground using flex-box to position different panels. Here is an example in JSBin, with the following html code: <div class="flex-box"> <div class="col" id="html-panel"> <p>html</p> </div& ...

Is there a way to customize the styles for the material UI alert component?

My journey with Typescript is relatively new, and I've recently built a snackbar component using React Context. However, when attempting to set the Alert severity, I encountered this error: "Type 'string' is not assignable to type 'Colo ...

Display an icon button when a user edits the text in a text field, and make it disappear once clicked on

Figuring out how to incorporate a v-text-area with an added button (icon) that only appears when the text within the text area is edited, and disappears once it is clicked on, has proven to be quite challenging. Below is a simplified version of my code to ...

Start up a server-side JavaScript instance utilizing Express

My journey into web programming has led me to learning JavaScript, Node.js, and Express.js. My ultimate goal is to execute a server-side JavaScript function (specifically a function that searches for something in a MySQL database) when a button is pressed ...

Perform a series of database queries one after the other, ensuring they are completed before

Although the database queries themselves are working fine, I am facing an issue with executing them sequentially in Node. Here is an example of the queries I need to execute in order: DELETE FROM myTable; INSERT INTO myTable(c1, c2, c3) VALUES (x, y, z); ...

Utilizing ng-href in Angular.js Template: A Guide

I am attempting to develop a simple Single Page Application (SPA) with just one index.html file that includes templates. However, I encountered an issue with the ng-href directive: <a ng-href="#/myPage">myPage</a> This works fine in index.h ...

There is no 'depto_modules.length' property in this row. How should I go about fixing this issue?

I have a table set up to display data from an associated table. The functionality is working fine, but I keep seeing a warning message when I apply certain filters: The warning states that the property depto_modules.length does not exist in the row. It ad ...

"Unleashing the Power of MongoDB's Dynamic $in

Is there a way to dynamically pass a list of strings to a $in clause in MongoDB? I attempted the following code, but it didn't work and I haven't been able to locate more information other than an example with hardcoded values. The restrictedUs ...

The MUI Select component requires two clicks to open its menu if another Select component's menu is already open

I have been developing an application with two dropdowns (Select components) positioned next to each other, denoted as A and B. When A is open and the user intends to click on B to open it, I observed that in the default behavior of material UI, the user ...

Incorporating Admob into the Intel XDK platform

After creating a customized 2048 game app for Android with Intel XDK, I encountered difficulties when trying to integrate AdMob into my application. Lack of coding knowledge may be the reason behind my struggles. I have been using the original codes for th ...

JavaScript isn't functioning properly after UserControl is loaded via Ajax

Thank you, Stilgar for helping me solve my issue. I created a javascript file and placed all my code in it. After adding this file to the UserControl and retrieving the UserControl's html, I used $("#DivID").html(UserControlHTML). Now everything is wo ...

What could be causing the excessive vertical spacing in an HTML list on Chrome: PHP output or CSS styling?

I'm having difficulty understanding why there is a significant vertical offset (around 170px) between one <li> element and the next. This issue seems to only occur in Chrome and not in Firefox, specifically within <li> elements when PHP co ...

AngularJS written plugin in Javascript

I developed an app using Rails and AngularJS. A startup has reached out to me about transferring the technology to their website, but they have limited tech resources. The goal is to create a seamless integration process. The idea is to make it similar to ...

Select options with disabled sorting feature

Is there a way to use CSS to sort disabled options in a select element? I would like all disabled options to appear at the bottom, with enabled options at the top. In the screenshot attached, you can see that enabled options are black and disabled options ...

When using Vuejs2, the list of autosize textareas connected to an expanding array of objects does not properly update their values

After binding https://github.com/jackmoore/autosize to textareas within a v-for loop, I've noticed an unexpected data persistence issue while expanding the array linked to that list: While inputs on the left side move downward as intended, new textar ...

The nightwatch.js script is halting operations once the test suite has been completed

Recently, I've implemented functional test automation using nightwatch.js. However, I encountered an issue where the test pauses after the test suite is completed, failing to end the process. Below is a snippet of the code: var afterSuite = function( ...

Regarding passing input into a JavaScript class method that is exported through the exports keyword

The inquiry at hand relates to ExtendScript code, however, I believe it should be independent of any specific javascript implementation. If we have the following in a JS library file (base64.js) exports.encode64 = encoder('+/'); //... function ...