Donny V. Donny V. - 7 months ago 23
jQuery Question

How do you create a toggle button?

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.

If theres no way of doing it just using css. Is there a way to do it using jQuery?


The good semantic way would be to use a checkbox, and then style it in different ways if it is checked or not. But there are no good ways do to it. You have to add extra span, extra div, and, for a really nice look, add some javascript.

So the best solution is to use a small jQuery function and two background images for styling the two different statuses of the button. Example with an up/down effect given by borders:


<a id="button" title="button">Press Me</a>


a {
    background: #ccc;
    cursor: pointer;
    border-top: solid 2px #eaeaea;
    border-left: solid 2px #eaeaea;
    border-bottom: solid 2px #777;
    border-right: solid 2px #777;
    padding: 5px 5px;       

a.down {
    background: #bbb;
    border-top: solid 2px #777;
    border-left: solid 2px #777;
    border-bottom:solid 2px  #eaeaea;
    border-right: solid 2px #eaeaea;



Obviously, you can add background images that represent button up and button down, and make the background color transparent.