Skip to content

Instantly share code, notes, and snippets.

@scan
Created October 14, 2011 12:40
Show Gist options
  • Save scan/1286994 to your computer and use it in GitHub Desktop.
Save scan/1286994 to your computer and use it in GitHub Desktop.
A Toggle Button with jQuery
$ ->
$('.toggle, .pressed').each ->
$('<input>', { type: 'hidden', name: $(this).data('name'), value: 'on' }).appendTo($(this))
$('.toggle').click ->
$btn = $(this)
$btn.toggleClass 'pressed'
if $btn.is '.pressed'
$('<input>', { type: 'hidden', name: $btn.data('name'), value: 'on' }).appendTo($btn)
else
$btn.find('input[type=hidden]').detach()
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.toggle {
width: 250px;
background: #ddf;
border-radius: 5px;
padding: 2px;
text-align: center;
box-shadow: 2px 2px black;
}
.pressed {
box-shadow: none;
margin-left: 2px;
margin-top: 2px;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
<script src="toggle.js" type="text/javascript"></script>
</head>
<body>
<form method="GET">
<div class="toggle pressed" data-name="toggle">
Toggle!
</div>
<input type="submit" />
</form>
</body>
</html>
(function() {
$(function() {
$('.toggle, .pressed').each(function() {
return $('<input>', {
type: 'hidden',
name: $(this).data('name'),
value: 'on'
}).appendTo($(this));
});
return $('.toggle').click(function() {
var $btn;
$btn = $(this);
$btn.toggleClass('pressed');
if ($btn.is('.pressed')) {
return $('<input>', {
type: 'hidden',
name: $btn.data('name'),
value: 'on'
}).appendTo($btn);
} else {
return $btn.find('input[type=hidden]').detach();
}
});
});
}).call(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment