Joshua Pearson Joshua Pearson - 7 days ago 6
HTML Question

Preventing Redirect to main page when clicking skip-link using jquery

The problem I am facing is that because of a tag in my html layout, I am being redirected to the main landing page when clicking a "skip to main content" link.

I am using the following JQuery to prevent this behavior, but it also prevents the direction to main content.

$(document).ready(function () {
$('#skip-link').click(function () {
$("#" + $(this).attr("href").slice(1) + "").focus()
alert("link Skipped")
event.preventDefault()
});
});


My question is, how can I prevent the redirection to the relative address, without using prevent Default.

Answer

Perhaps something like this:

$(document).ready(function () {
    $('#skip-link').click(function (e) {
        e.stopPropagation();
        $("#" + $(this).attr("href").slice(1) + "").focus();
        alert("link Skipped");
    });
});

UPDATE:

Ok if I understood you correctly, this is what you want, simply:

<a href="#skip-link">Jump to main</a>
<a name="skip-link"></a><div class="row" id="anchor">blabla</div>

or jQuery:

<a id="skip-link" href="#anchor">Jump to main</a>
<div class="row" id="anchor">blabla</div>

$(document).ready(function () {
    $('#skip-link').click(function (e) {
        e.stopPropagation();
        var hash = $(this).attr("href").slice(1);
        alert(hash);
        $("#" + hash).focus();
        $("#" + hash).css('background-color', 'red');
    });
});

https://jsfiddle.net/75k7u4w3/

Comments