Trying to get the door’s image to change from a closed door svg image to an open door svg image
when the status goes from closed to open in my home automation dashboard. Seeking help.
<!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">
<li class="dashboard_item kitchen">
<h4>Kitchen</h4>
<img src="./moon.svg" width="40px" id="toggle-img" height="40px" alt="">
<p id="kitchen-light">OFF</p>
<button id="kitchen-btn">Toggle</button>
</li>
<li class="dashboard_item frontdoor" >
<h4>Front Door</h4>
<img src="./door-closed.svg" width="40px" id="toggle-img6" height="40px" alt="">
<p id="frontdoor-door">CLOSED</p>
</li>
</ul>
</body>
</html>
This is what I’ve been trying in javascript:
function togglefrontdoor() {
var status = document.getElementById("frontdoor-door").innerHTML;
if (status === "CLOSED")
document.getElementById('toggle-img6').innerHTML = './door-closed.svg';
else if (status === "OPEN")
document.getElementById('toggle-img6').innerHTML = './door-open.svg';
}
2
Answers
Here the example which toggle the image button by reusing part of your element.
Click the Toggle button to switch the svg.
Your
togglefrontdoor()
is not really functioning well because the content oftoggle-img6
is always CLOSED, you need to update it as well while updating the svg.Or maybe you have another function that call
togglefrontdoor()
like, I don’t knowBut anyhow, I modify your
togglefrontdoor()
function just to make the example works.Happy coding!