I want to create a toggle button in html using css. I want it so that when you click on it , it stays pushed in and than when you click it on it again it pops out.
You could use an anchor element (<a></a>
), and use a:active and a:link to change the background image to toggle on or off. Just a thought.
Edit: The above method doesn't work too well for toggle. But you don't need to use jquery. Write a simple onClick javascript function for the element, which changes the background image appropriately to make it look like the button is pressed, and set some flag. Then on next click, image and flag is is reverted. Like so
var flag = 0;
function toggle(){
if(flag==0){
document.getElementById("toggleDiv").style.backgroundImage="path/to/img/img1.gif";
flag=1;
}
else if(flag==1){
document.getElementById("toggleDiv").style.backgroundImage="path/to/img/img2.gif";
flag=0;
}
}
And the html like so
<div id="toggleDiv" onclick="toggle()">Some thing</div>
If you want a proper button then you'll need some javascript. Something like this (needs some work on the styling but you get the gist). Wouldn't bother using jquery for something so trivial to be honest.
<html>
<head>
<style type="text/css">
.on {
border:1px outset;
color:#369;
background:#efefef;
}
.off {
border:1px outset;
color:#369;
background:#f9d543;
}
</style>
<script language="javascript">
function togglestyle(el){
if(el.className == "on") {
el.className="off";
} else {
el.className="on";
}
}
</script>
</head>
<body>
<input type="button" id="btn" value="button" class="off" onclick="togglestyle(this)" />
</body>
</html>
You can just use toggleClass()
to track state. Then you check if button element has the class, like this:
$("button.toggler").click( function() {
$me = $(this);
$me.toggleClass('off');
if($me.is(".off")){
alert('hi');
}else {
alert('bye');
}
});
And I use the button
element for buttons for semantic reasons.
<button class="toggler">Toggle me</button>
I would be inclined to use a class in your css that alters the border style or border width when the button is depressed, so it gives the appearance of a toggle button.
As far as I was searching for answer too, and wanted to acomplish it with CSS. I found solution by CSS NINJA
It is a nice impelmentation of <input type="checkbox">
and some css
Live demo!
Although it is not working in IE 8 you could implement selectivizr! and fix CSS where uses opacity
to filter
to make it work in IE.
EDIT 2014:
for new toggle buttons I do use solution found on Lea Verou blog visually similar to iOS checkbox
Try;
<li>Text To go with Toggle Button<span class = 'toggle'><input type = 'checkbox' class = 'toggle' name = 'somename' id = 'someid' /></span></li>
And make sure in the
<head><link rel = 'stylesheet' src = 'theme.css'> (from jqtouch - downloadable online)
<link rel = 'text/javascript' src = 'jquery.js'> (also from jqtouch)
</head>
Remember when you are coding this, only somename
and someid
can change in the input tag, otherwise it doesn't work.