Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Two-state button

Tags:

css

I need a button-like control that has a checked property, so that when clicked it stays pressed. Something like the "Purge responses" button in the example image below.

How can I do this in CSS? I'm a CSS newbie. Can someone provide an example or point to one that is similar to this?

PS: I know that I need to use Javascript to update a boolean variable that holds the state of the button, and dynamically apply a style to the button. My problem is more like how to create a button that contains a checkbox , as I have only one image for background.

https://i.sstatic.net/vBV6F.png

like image 740
panait.distrati Avatar asked Sep 06 '25 03:09

panait.distrati


2 Answers

To reduce JavaScript coding, it's best to nest a checkbox inside a label in the HTML. This will make it automatically handle the checking/unchecking of the checkbox when you click on the label.

/* If you have more experience in JavaScript, I recommend not binding the change event this way, I didn't bother much about this part, since I guess it isn't part of the question */
    function change_state(obj){
        if (obj.checked){
            //if checkbox is being checked, add a "checked" class
            obj.parentNode.classList.add("checked");
        }
        else{
            //else remove it
            obj.parentNode.classList.remove("checked");
        }
    }
    /* this is the style of an unchecked "button" */
    .input-check{
        display:inline-block;
        height:20px;
        padding:5px 8px;
        background:green;
        width:70px;
        color:white
    }
    /* This is the style for a checked "button" */
    .input-check.checked{
        background:red;
        color:black;
        font-weight:bold
    }
    /* Hide the checkbox */
    .input-check input{
        display:none
    }
<label class="input-check"><input onchange="change_state(this)" type="checkbox" value="something" name="test"/> click me </label>
like image 92
Dan Avatar answered Sep 07 '25 19:09

Dan


Why don't you just style a checkbox to look like a button?

Then you can use the :checked CSS psudeo selector to style it the way you want without adding classes through javascript.

Here's an elaborate example in CodePen: http://codepen.io/arjabbar/pen/csafj

like image 27
arjabbar Avatar answered Sep 07 '25 21:09

arjabbar