Dakifiz
Dakifiz

Reputation: 13

How to keep focus on a selected button

there are two buttons on the page, when you click on one, it changes color.

How to make this focus not disappear after clicking on the empty field next to it?

<button id="button1">Text 1</button>
<button id="button2">Text 2</button>

.button1 {
height: 48px;
width: 240px;}

.button1:hover {
background-color: red;}

.button1:focus {
background-color: green;}

.button2 {
height: 48px;
width: 240px;}

.button2:hover {
background-color: red;}

.button2:focus {
background-color: green;}

Upvotes: 0

Views: 2038

Answers (2)

Mihai Matei
Mihai Matei

Reputation: 24276

You can do it with HTML and CSS only by styling the labels of radio inputs as the following suggestion.

The advantage of this implementation is that you don't have to maintain another element (by javascript) if you need the button value to be submitted through a form.

span {
    display: inline-block;
    position: relative;
}

span > input[type=radio] {
    visibility: hidden;
    position: absolute;
}

span > label {
    padding: 5px 10px;
    border: solid 1px #ccc;
    cursor: pointer;
}

span > label:hover {
    background-color: #fcfcfc;
}

span > input[type=radio]:checked + label {
    background-color: green;
    color: white;
}
<span>
    <input name="my-button" value="1" type="radio" id="my-button-1" />
    <label for="my-button-1">Text 1</label>
</span>
<span>
    <input name="my-button" value="2" type="radio" id="my-button-2" />
    <label for="my-button-2">Text 2</label>
</span>

Upvotes: 2

prettyInPink
prettyInPink

Reputation: 3444

You could do so with Javascript. Note that you are also adding ids to your buttons but in your styles you are targeting classes.

let btns = document.querySelectorAll('button');

btns.forEach((btn)=> {
    btn.addEventListener('click', function() {
        if(document.querySelector('button.active')){
         document.querySelector('button.active').classList.remove('active');
        }
        btn.classList.add('active');
    });
});
#button1 {
height: 48px;
width: 240px;}

#button1:hover {
background-color: red;}

#button1:focus, #button1.active {
background-color: green;}

#button2 {
height: 48px;
width: 240px;}

#button2:hover {
background-color: red;}

#button2:focus, #button2.active {
background-color: green;}
<button id="button1">Text 1</button>
<button id="button2">Text 2</button>

Upvotes: 2

Related Questions