comu
comu

Reputation: 921

CSS Button :focus pseudo class

How Would I make it so that when I click a button, the button stays that color until another button is clicked?

To clarify, imagine you have a text box. When you click it, you can add a border because you have it like input:focus{border:#000} and when the input loses focus or another text box is clicked, the border properties go back to the default.

How would I accomplish this with a button. I feel like I'd need to use :after or something.

My Code

button.top_bar {
    background-color:#E3E3E3;
    border:#DCDCDC 1px solid;
    border-radius:3px;
    height:40px;
    display:block;
    color:#000;
    postion:relative;
    display:block;
    float:left;
    top:5;
    text-transform:capitalize;
    font-family:Arial;
    font-weight:bold;
    cursor:pointer;
    margin-left:15px;
}

button.top_bar:hover {
   border:#9F9F9F 1px solid;
}

button.top_bar:focus {
    border:#9F9F9F 1px solid;
}

Upvotes: 2

Views: 12036

Answers (2)

James Daily
James Daily

Reputation: 597

Unlike text inputs, some browsers don't seem to grant focus when button elements are clicked. Add to your button element an attribute onclick="this.focus()" to force the issue. No jQuery needed :-)

Upvotes: 1

James Rasmussen
James Rasmussen

Reputation: 661

The only way I can think of doing this is with jQuery, or some sort of Javascript. Here's how I would do it: I would control it via a class (let's call it ".selectedBorder"). Then on click, grab all your buttons that you have, and turn off the borders for all of them, then just add it on the clicked one. Here's an example:

//first you grab the click event for the button(s)
$("#buttons").click(function(){

    //we remove all the borders from all the buttons
    $("#buttons").removeClass("selectedBorder");

    //Now we add the border to the button that's been clicked
    $(this).addClass("selectedBorder");

});

That should do the trick. Just add that in a javascript tag or an external file and include it, and you should be good to go. Hope that helps.

Upvotes: 2

Related Questions