简体   繁体   中英

To re-set focus on Anchor Tag

I have used anchor tags on my master page. During TAB key press when focus occurs on particular anchor tag, and then on ENTER key press, it redirects to specific linked page. Anchor tag is working fine. But what I want is that as it opens specific linked page and page is re-loaded then focus should remain on that specific link. So that on next TAB key press navigation/focus moves to next anchor tag.But what currently happening is that when we press ENTER key, that anchor tags link open and on TAB key press default Navigation starts from URL.

<div title="Main" >
            <a href="/Home.aspx" id="home">

                <div class="link-title">
                    Home
                </div>
            </a>
        </div>
        <div title="Contact" >
            <a href="/Contact.aspx" id="contact>

                <div class="link-title">
                    Contact
                </div>
            </a>
        </div>

CSS Code is mentioned below:

/* To set keyboard focus on Tab press*/
a:focus
{
    outline: 1px dotted black;
}

If I got you correctly, here is my offer: Add a data attribute to the body element (for example) of each page and set value, for example index of each anchor tag, or something as key , then on page_load with jquery read that data attribute and set the focus depend on the value.

<body data-index='1'>
// rest of the html

JS:

var index = $('body').data('index');
$anchors.eq(index).focus(); // you need to find `anchor` tags first.

Hope this help.

I think you are expecting this solution.

Try this way using keydown event for tab key alone.

 $(function () { $("a").keydown(function (e) { if (e.which == 9) { var ele = $("a"); var len = ele.length; var index = ele.index(this); if (index == (len - 1)) { ele.eq(0).focus(); e.preventDefault(); //To prevent event bubbling } } }); }); 
 a:focus { color: yellow; outline: 1px dotted black; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <div title="Main"> <a href="/Home.aspx" id="home" target="_blank"> <div class="link-title"> Home </div> </a> </div> <div title="Contact"> <a href="/Contact.aspx" id="contact" target="_blank"> <div class="link-title"> Contact </div> </a> </div> <div title="About"> <a href="/About.aspx" id="about" target="_blank"> <div class="link-title"> About </div> </a> </div> 

Hope this helps you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM