Created
October 14, 2011 12:40
-
-
Save scan/1286994 to your computer and use it in GitHub Desktop.
A Toggle Button with jQuery
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ -> | |
$('.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() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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