Forum Moderators: open

Message Too Old, No Replies

Semantic element to create a toggle and best way to undo a function

         

Rain_Lover

10:19 am on Mar 5, 2014 (gmt 0)

10+ Year Member Top Contributors Of The Month



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: [jsfiddle.net ]

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?

Fotiman

7:46 pm on Mar 5, 2014 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I would say that if you're toggling between 2 values (on/off), then a checkbox makes the most sense since it has 2 possible states (checked/not checked).

In your example, your elements get their default style from the CSS. You're then overriding that by explicitly assigning to the style property of that element. To undo, just set the style property back to nothing.

if (box.checked) {
first.style.color = 'red';
second.style.border = '2px dotted blue';
third.style.background = 'olive';
} else {
first.style.color = '';
second.style.border = '';
third.style.background = '';
}

Also, for a checkbox you probably want to run this in the onclick event, not the onchange event.

Fotiman

10:06 pm on Mar 5, 2014 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



And for reference, the updated jsfiddle:
[jsfiddle.net...]

Rain_Lover

3:29 am on Mar 6, 2014 (gmt 0)

10+ Year Member Top Contributors Of The Month



Thanks so much! :)