7
I suggest separating the question into two and having a question aside for the server part. I believe there are plenty of examples of how to do.
Note: I ended up making a component of this in React on Github
The client side part you can do as in the example below:
var estado = document.getElementById('estado');
$('#onoff1').on('change', function() {
var el = this;
estado.innerHTML = el.checked ? 'ligado' : 'desligado';
// aqui podes juntar a lógica do ajax
$.ajax({
url: "some.php",
data: {
estado: this.checked
}
}).done(function(msg) {
if (msg == 'failed') return el.checked = !el.checked; // caso o servidor retorne "failed" mudar o estado do botão
else alert("Info gravada: " + msg);
});
});
.onoff input.toggle {
display: none;
}
.onoff input.toggle + label {
display: inline-block;
position: relative;
box-shadow: inset 0 0 0px 1px #d5d5d5;
height: 60px;
width: 100px;
border-radius: 30px;
}
.onoff input.toggle + label:before {
content: "";
display: block;
height: 60px;
width: 60px;
border-radius: 30px;
background: rgba(19, 191, 17, 0);
transition: 0.1s ease-in-out;
}
.onoff input.toggle + label:after {
content: "";
position: absolute;
height: 60px;
width: 60px;
top: 0;
left: 0px;
border-radius: 30px;
background: #fff;
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.2), 0 2px 4px rgba(0, 0, 0, 0.2);
transition: 0.1s ease-in-out;
}
.onoff input.toggle:checked + label:before {
width: 100px;
background: #13bf11;
}
.onoff input.toggle:checked + label:after {
left: 40px;
box-shadow: inset 0 0 0 1px #13bf11, 0 2px 4px rgba(0, 0, 0, 0.2);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="onoff">
<input type="checkbox" class="toggle" id="onoff1">
<label for="onoff1"></label>
</div>
<p id="estado">desligado</p>
jsFiddle: https://jsfiddle.net/d2a9vLpj/
The change and color part of the button is HTML + CSS only. Javascript would only be to know when the button changes and send to the server.
A suggestion without the tag
<label>
and more simplified https://answall.com/q/277235/3635– Guilherme Nascimento