Open Page with a Key

Asked

Viewed 72 times

-1

On the page, who press key z opens my URL.

I don’t know if it’s possible, but I wish I didn’t have to Alt, Ctrl and/or Shift.

#teclas {display:none;}
<div id='teclas'>
<a accesskey='z' href='#zenphone'></a>
</div>

The code I’m using above has to press Alt+Z or something else on another browser or operating system, I wanted you to open this link with just pressing a letter or number from the keyboard.

1 answer

1

Yes! You can hear the key click z and open a specific URL. But for this you should use Javascript. And in this case it would look like this:

window.onload = () => {
  document.addEventListener("keypress", function(event) {

    // Pode ver a lista dos códigos  [aqui][1]
    if (event.key === 'z' || event.keyCode === 122) {

      let href = document.getElementById("teclas-z").getAttribute("href"); // Busca o URL

      window.open(href, '_blank'); // Abre a URL numa nova aba

    }
  })
};
#teclas {
  display: none;
}
<div id="teclas">
  <a accesskey="z" href="https://www.google.com" target="_blank" id="teclas-z"></a>
</div>

You can see the code list here

  • It didn’t work here not, I tested in more than one browser, I put the number of the key codes and nothing

  • @Yasmingulosa troque document.getElementById("teclas-z")[0] for document.getElementById("teclas-z"), for document.getElementById returns only one element, no array, so [0] is unnecessary.

  • now worked without the [0] worth

  • @Guilhermenascimento Thank you.

  • just missed to mark as right @Yasmingulosa

Browser other questions tagged

You are not signed in. Login or sign up in order to post.