PDA

View Full Version : Semantic element to create a toggle and best practice to undo a function



Rain Lover
03-05-2014, 10:14 AM
Sample:


<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<title>Toggle</title>
<style>
#first {
color: blue;
}
#second {
border: 1px solid green;
}
#third {
background: tan;
}
</style>
</head>

<body>
<label for="box">Toggle</label>
<input type="checkbox" id="box" onchange="toggle();">
<div id="first">First</div>
<div id="second">Second</div>
<div id="third">Third</div>
<script>
function toggle() {
var box = document.getElementById('box');
var first = document.getElementById('first');
var second = document.getElementById('second');
var third = document.getElementById('third');
if (box.checked) {
first.style.color = 'red';
second.style.border = '2px dotted blue';
third.style.background = 'olive';
} else {
first.style.color = 'blue';
second.style.border = '1px solid green';
third.style.background = 'tan';
}
}
</script>
</body>

</html>

DEMO (http://jsfiddle.net/RainLover/3fNre/)

I wonder if an input checkbox is the right element to create a toggle. I also want to know how to undo what I have in the if clause: in else do I have to repeat my stylesheet or is there a shorter neater way to get back to the initial state?