Switching display with a toggle mechanism

I've been experimenting with a home automation dashboard and I'm in need of some guidance. How can I make the image change when the button is toggled ON and OFF? I have a sun svg for ON and a moon svg for OFF.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard</title>
    <!-- Add font from Google fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300&display=swap" rel="stylesheet">
    <!-- Link CSS style sheet to html document -->
    <link rel="stylesheet" href="style.css">
    <!-- Link JavaScript file to html document -->
    <script src="mqttws31.js"></script>
    <script src="dashboard.js"></script>
  </head>
  <body>
    <div class="header">
      <h1>Home Automation Dashboard</h1>
    </div>
    <hr>
    <div id="messages"></div>
    <div id="status"></div>
    <hr>
    <ul class="dashboard">
    <ol class="b"> 
      <li class="dashboard_item kitchen">
      <img src="./moon.svg" width="40px" height="40px" alt="">
        <h4>Kitchen</h4>
        <p id="kitchen-light">OFF</p>
        <button id="kitchen-btn">Toggle</button>
      </li>
      <ol class="b"> 
        <li class="dashboard_item frontdoor" > 
        <img src="./door-closed.svg" width="40px" height="40px" alt="">
        <h4>Front Door</h4>
        <p>CLOSED</p>
      </li>
    </ul>
  </body>
</html>

<!-- javascript variable declaration -->

var KitchenState = true;

var el = document.getElementById("kitchen-btn");
el.addEventListener('click', function() {
      document.getElementById("kitchen-light").innerHTML = KitchenState ? "ON" : "OFF";
      KitchenState = !KitchenState;
});

I've attempted several online examples without success so far.

Answer №1

Make sure to assign an id attribute to the image and then manipulate it in a similar manner as you would change the innerHTML of an element. When dealing with images, simply adjust the src attribute accordingly.

<script>
    var KitchenState = true;

var el = document.getElementById("kitchen-btn");
el.addEventListener('click', function() {

      document.getElementById("kitchen-light").innerHTML = KitchenState ? "ON" : "OFF";
      document.getElementById('toggle-img').src = KitchenState ? './sun.svg' : './moon.svg'
     
      KitchenState = !KitchenState;
});
    </script>


 <img src="./moon.svg" width="40px" id="toggle-img" height="40px" alt="">

Answer №2

Use method .setAttribute or property .src Include id kitchen-icon to the <img> tag for icon

Here is a sample code snippet:


var KitchenState = true;

var el = document.getElementById("kitchen-btn");
el.addEventListener('click', function() {
      document.getElementById("kitchen-light").innerHTML = KitchenState ? "ON" : "OFF";

      document.getElementById('kitchen-icon').src = KitchenState ? './moon.svg' : './sun.svg'

      KitchenState = !KitchenState;
})

Answer №3

When considering your query, it appears that the code below might be of assistance

let btnAll = document.getElementByTagName('button')
let conAll = document.getElementByClassName('content')
let btnAllLen = btnAll.length

//Implementing a callback function for each button click event
for (let i = 0; i < btnAllLen; i++) {
  !(function(n) { // Setting up click event listeners
    btnAll[n].addEventListener('click', function() {
      for (let j = 0; j < btnAlllen; j++) {
        btn[j].className = ""
        conAll[j].style.display = "none"
      }
      this.className = "active"
      conAll[n].style.display = "block"
    })
  })(i)
}
.main {
  text-align: center;
}

button:focus {
  outline: none;
}

nav {
  margin-top: 30px;
  box-sizing: border-box;
}

button {
  background: white;
  border: none;
  height: 36px;
  line-height: 36px;
  width: 80px;
  text-align: center;
  border: 1px solid lightgray;
  border-radius: 4px;
  cursor: pointer;
}

nav>button:not(:first-child) {
  margin-left: 15px;
}

.active {
  background: black;
  color: white;
}

.content {
  margin-top: 40px;
}

.content>p {
  display: none;
}
<div class="main">
  <nav>
    <button class="active">content 1</button>
    <button>content 2</button>
    <button>content 3</button>
    <button>content 4</button>
  </nav>
  <div class="content">
    <p style="display: block;">content1</p>
    <p>content2</p>
    <p>content3</p>
    <p>content4</p>
  </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

How to choose multiple checkboxes in AngularJS by utilizing the shift key and mouse click feature?

Is it feasible to utilize shift and mouse click for selecting multiple elements on a table using AngularJS? In my table, the first column consists of checkboxes and I am interested in employing the SHIFT key along with mouse clicks to select several rows ...

Tips on storing a blob (AJAX response) in a JSON file on your server, not on the user's computer

After researching extensively on creating a URL from or downloading a blob in a computer, I require a unique solution: (1) Save a blob in own server into a JSON file, (2) Optimize the way to update a database using the data stored in the JSON. My attemp ...

Adjusting the rotation transform by deleting and reapplying canvas is causing the chart to not display data after redrawing

I am facing a challenge with my previous issue and I am exploring different solutions. One approach I am considering is to remove the canvas element completely and then re-add it, effectively resetting all rotations on the canvas. Although this method alm ...

The time.js library is providing inaccurate second values for the given date and time

Utilizing the moment.js library along with the Timezone and BusinessDays extensions in Vue.js, I am developing a datetime format for storing in a MySQL database. Here is the code snippet: import moment from 'moment-timezone' ...

Ways to ensure that a div, header, container, and other elements completely cover the viewport

Currently, I am attempting to create a header that spans the entire viewport regardless of screen size. This header will be split horizontally into 3 equal sections, each occupying one third of the header space. I experimented with setting the header hei ...

Finding the difference between a PHP date and a JavaScript date

I am currently working on a project using PHP Laravel framework and VueJS. I need to calculate the time difference between the server time and client time in order to process certain data timeouts using JavaScript on the client browser. Can someone guide ...

Retrieve JSON data using AngularJS

Can someone guide me on how to make a GET request to my API endpoint and handle the JSON response in my code? Sample Controller.js Code: oknok.controller('listagemController', function ($scope, $http) { $scope.init = function () { ...

Importing events from the calendar causes disarray in other data columns when sorted by date

I have a unique code that successfully imports my shared Google Calendar into a spreadsheet. In my medical office, I manage all appointments through a master Calendar. The calendar data includes start time, location, description, and title in columns B, ...

As soon as I execute this code, the Meta slider vanishes without a trace

I am experiencing a strange issue with my Meta Slider on the homepage and I can't figure out why. Every time I add a certain code snippet, my drop-down text feature starts working but the Meta slider disappears. However, as soon as I remove the code, ...

Oh no! It seems like the build script is missing in the NPM

https://i.stack.imgur.com/el7zM.jpg npm ERR! missing script: build; I find it strange, what could be causing this issue? Any suggestions? I have included the fullstack error with the package.json. Please also review the build.sh code below. Fullstack err ...

"How can I display validation errors for email and fax in each row of loop items using Angular? Specifically working with Angular 8

In my Angular8 project with Bootstrap, I have created input fields dynamically from an array using a loop. When there is a validation error for the email or fax number input, the error is displayed. However, I noticed that if there is an error in the first ...

Element not being located by Selenium - TimeoutException

Currently, I am utilizing Selenium to input data into a specific field and then extract information from the results. The process of entering the data works fine, including accepting the cookie pop-up prompt, however, there seems to be an issue with locati ...

Guide to Using Bootstrap 4 for User Information: Best Practices and Steps to Follow

I'm currently working on a design layout using bootstrap 4 alpha version and I must say, the cards feature is quite impressive. Specifically, I have this section within the layout where I want to align the phone number and email address info on the s ...

Guide to selecting a checkbox in Vue.js 2 based on a specific value?

I'm currently working on setting up a roles and permissions system for my application. For the frontend, I am using Vue.js2 and for the backend, Laravel 5.4. Below is the allRoles array containing all roles fetched from the database: data: { // ...

Utilizing conditional statements like if/else and for loops within a switch statement in JavaScript allows for

I am currently developing a request portal that involves dynamic checkboxes, labels, and textboxes that are dependent on an option list. As a beginner in javascript, I am facing challenges with creating conditional statements. I have managed to make progr ...

Custom Homepage with Integrated Google Web Search and Autocomplete Feature

Is there a way to incorporate the standard Google web search with autocomplete into my own webpage, without using a custom search engine like www.google.com? I have been unable to find any examples or guides on how to accomplish this. All the resources see ...

"Initiate an Ajax call in Full Calendar before an event is displayed on the calendar

I need guidance on how to integrate ajax calls with the Full Calendar documentation. Specifically, I want to make an ajax call to a WordPress database before each event is rendered on the calendar. The response from the call will determine the color of the ...

Is there a way to extract variables from a MySQL database and integrate them into a JavaScript function?

Hello everyone, I am looking to add markers on a map. In order to do this, I need to extract longitude and latitude from a database table. 1- I have used JavaScript to display the map (Google Maps). var map; var initialize; initialize = function( ...

Checkbox in Angular FormGroup not triggering touched state

There seems to be an issue with the Angular form when checking if the form is touched, especially in relation to a checkbox element. Despite the value of the checkbox changing on click, I am seeing !newDeviceGroup.touched = true. I'm not quite sure wh ...

Creating a reset or refresh button with JavaScript: Step-by-step guide

Can someone please help me figure out how to create a button that will refresh the page while also resetting all values to their default settings? ...