Domanda

i know how to make div to refer a location when it is clicked

<div onclick="location.href='newurl.html';" tabindex="0"><a>Text</a></div>

But it work when only clicked by mouse, but if i want to navigate through keyboard and press "Enter key" or "Space key" it wont work..

So what i want is something like this

<div onkeydown="location.href='newurl.html';" tabindex="0"><a>Islam</a></div>

and i dont wanna write code somewhere else like js file

È stato utile?

Soluzione

Just attach both listeners to the div, and in onkeydown check the pressed key:

<div
  onkeydown="if(event.which===32||event.which===13) location.href='newurl.html';"
  onclick="location.href='newurl.html';"
  tabindex="0"
>
    <a>Islam</a>
</div>

A live demo at jsFiddle.

Altri suggerimenti

I am not completely sure what you want, but maybe your are looking for event.keyCode. It gives you a code of pressed key and you can easily check Enter and Space.

<div onkeydown="if(event.keyCode==13||event.keyCode==32)location.href='newurl.html'; " onclick="location.href='newurl.html';" tabindex="0">Link</div>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top