Home > Software design >  How to set focus on an image on page load
How to set focus on an image on page load

Time:06-18

Is there a way to set the focus on an on page load? I have found documentation stating to use the autofocus attribute but the documentation says that attribute only applies to input, button, textarea, and select.

Thanks.

CodePudding user response:

You can try scrollIntoView method on window onl oad

window.onload=function(){
    document.getElementById("ID_OF_IMAGE").scrollIntoView();
}

CodePudding user response:

I think you looking for something like that:

window.addEventListener('load', function() {
    document.querySelector(".classFromImage").focus();
})

CodePudding user response:

What you could do is search for the img element with the autofocus attribute and set the focus after the DOM is read. You also need to set the tabindex to get that working.

I would only search for img[autofocus] so that you don't mess too much around with the default behavior.

window.addEventListener('DOMContentLoaded', function() {
  let elm = document.querySelector("img[autofocus]")
  if (elm) {
    elm.focus()
  }
})
img {
  width: 100px;
  height: 100px;
  display: inline-block;
}

:focus {
  border: 4px solid red;
}
<img autofocus tabindex="0">

CodePudding user response:

You can focus a nonfocusable element by adding tabindex="0" attribute to the tag and use focus() method with js.

<img  tabindex="0" src="#"/>
window.addEventListener('load', function() {
    document.querySelector(".focusable").focus();
})
  • Related