I'm working on an Arduino-based system where LEDs will be turned on/off using web server (with ESP8266). I want to add a toggle switch in the HTML page so that LED will be on/off using this slide button.
What I have done so far is the toggle switch is created in HTML and added some CSS that I found on the web. Now as you can see in the code attached, 'id' is defined for the button. Now, this id is sent to the Arduino when I click to the button and used to turn the LED on/off.
For example, if 'id'="111" is sent, LED is ON and if 'id'="110", LED is OFF. So the problem is; whenever I click the switch, the same id(111) is sent to the server since the id of the switch is hard coded. Therefore I can not turn off the LED.
All in all, how can I set the id="110" when I click again the switch to turn it off? So LED will be off too. Please let me know your suggestions to make the system more dynamic, and how should I continue. I thought about setting p = p -1 when the button is turned off, but I lost my way.
Thanks,
$(document).ready(function(){
$('.switch').click(function(){
var p = $(this).attr('id');
$.get("IPADDRESS", { pin: p });
$(this).toggleClass("switchOn" );
});
});
.wrapper{
width:500px;
margin:0 auto;
}
.switch{
width:200px;
height:100px;
background:#E5E5E5;
z-index:0;
margin:0;
padding:0;
appearance:none;
border:none;
cursor:pointer;
position:relative;
border-radius:100px;
}
.switch:before{
content: ' ';
position:absolute;
left:5px;
top:5px;
width:190px;
height:90px;
background:#ffffff;
z-index:1;
border-radius:95px;
}
.switch:after{
content:' ';
width:88px;
height:88px;
border-radius:86px;
z-index:2;
background:#FFFFFF;
position:absolute;
transition-duration:500ms;
top:6px;
left:6px;
box-shadow:0 2px 5px #999999;
}
.switchOn, .switchOn:before{
background:#4cd964; !important;
}
.switchOn:after{
left:105px;
}
<head>
<title>Smart Home System</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<label>
<div id="111" class="switch">
</label>
</body>