Search code examples
javascripthtmllocation-href

Keydown on DIV to refer some Location


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


Solution

  • 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.