Thursday, October 22FreeJQuery

How To Add Keyboard Shortcut to Anchor Tag Using jQuery

Add Keyboard Shortcut Using JQuery

In This Article We Are Discuss About how to add Keyboard Shortcut Using JQuery Making a user friendly website can be quite a challenging task. There are many areas where user interactions can improve and become friendlier. One area that can almost always be improved is navigation, and one great way to do this is by adding keyboard shortcuts to anchor elements that allow the user to open hyperlinks via the keyboard instead of the mouse. Keyboard shortcuts improve productivity by enabling users to accomplishing tasks more quickly and without much effort. In this post, we’ll learn how to add keyboard shortcuts to anchor tags using jQuery.

HTML Markup

First, let’s take a look at the HTML markup. There are 3 anchor tags defined with href attribute set to external websites like Google, Facebook and Twitter respectively. There is also a unique ID that is defined for every anchor tag:


Use Keyboard Keys G, F or T to visit respective websites.




<li><a id=”lnkGoogle” href=””>Google</a></li>

<li><a id=”lnkFacebook” href=””>Facebook</a></li>

<li><a id=”lnkTwitter” href=””>Twitter</a></li>


jQuery Code

To implement this functionality, we need to capture the keys and identify them. To capture the keys, attach a keyup() event to the document itself and then check for the key code of the pressed key. If the key code matches with “G, g, F, f, T, t” then navigate to the respective website.

The following is the outline of the jQuery solution:

  • First, capture the keyup event and attach it to the document object. In the keyup event, the key is detected using the keyCode or charCode.
  • The keycode for “G” and “g” is 71 and 103, for “F” and “f” is 70 and 102 and for “T” and “t” is 84 and 116.  Since we already know the keycodes, create a switch case logic block based on these keycodes. 
  • This method is responsible for opening the href URL.  It accepts the anchor tag object as parameter, so we pass the same using the ID of the anchor tag.
  • Inside the open Website() method, replace window.location with anchor tag href value. This will open the URL in the same tab/window. The window.location object can be used to get the current page address (URL) and to redirect the browser to a new page.

complete jQuery code Here

Read More

Leave a Reply

Your email address will not be published. Required fields are marked *