Home > Software design >  How to focus one button by default?
How to focus one button by default?

Time:11-16

I'm having trouble with 2 buttons that each toggles different "div" elements. I want to focus "button 1" by default. How do I do that? Autofocus is not working.
Here's the HTML code

<div >
     <button  data-target="#block-1" autofocus>1</button>
     <button  data-target="#block-2">2</button>
 </div>

Here's the JS code

let $blocks = $(".block-card");

$(".filter-btn").on("click", (e) => {
  let $btn = $(e.target).addClass("active");
  $btn.siblings().removeClass("active");

  let selector = $btn.data("target");
  $blocks.removeClass("active").filter(selector).addClass("active");
});

CodePudding user response:

If autofocus is not working due to browser behavior or styling of other elements, you can still use Javascript to set focus.

Example:

document.querySelector(".filter-btn.active").focus({focusVisible: true});

{focusVisible: true} is optional here and it forces browser to make the focus visible.

There is a jQuery equivalent, but it seems that it does not take the optional config.

Example:

$(".filter-btn.active").focus();

Some CSS can be added to making testing easier.

Example:

button:focus {
  color: crimson;
}

button:focus-visible {
  outline: 2px solid crimson;
  border-radius: 3px;
}

When running the following example, note that the first button should be focused.

Full example: (run it in live with button below)

document.querySelector(".filter-btn.active").focus({focusVisible: true});
button:focus{ color: crimson }

button:focus-visible {
    outline: 2px solid crimson;
    border-radius: 3px;
}
<div >
     <button  data-target="#block-1">1</button>
     <button  data-target="#block-2">2</button>
 </div>

Hope this will help!

  • Related