rahul uttarwar
rahul uttarwar

Reputation: 19

CSS equivalent of DOM focus()

I want to set the focus on a button on particular event. The pseudo code for this can be,

if (event == "EventX") {
  document.getElementById('myAnchor').focus();
}

is there a CSS equivalent for document.getElementById('myAnchor').focus();?

Upvotes: 0

Views: 273

Answers (2)

BoltClock
BoltClock

Reputation: 723388

You can't change the state of an element using CSS. While CSS can style elements based on specific states, it cannot actually trigger those states. To do that, you use JavaScript, not CSS, since the DOM APIs are implemented in JavaScript, not CSS.

Upvotes: 2

Mr. Alien
Mr. Alien

Reputation: 157284

I think am getting confused here, as @Paulie commented, I think what you are looking for is to autofocus an element on load than you cannot do that with CSS, if you want, you need can use autofocus attribute on the element you want to get the focus on, like

<input type="text" autofocus />

If you want to style the focused element then you need to use :focus pseudo

input[type=text]:focus {
    border: 1px solid red;
}

Demo

As I read your id it says myAnchor so you can write your selector like — to make it more specific

#myAnchor:focus {
    /* Styles goes here */
}

Upvotes: 1

Related Questions