Damien
Damien

Reputation: 621

Removing anchor tags from URL

I'm using a bunch of anchor tags for mobile browsing due to a very long page but when the anchor tag is clicked it adds it to the url. Here is a small mock,

<a href="#anchor">page down</a>

<span id="anchor"></span>

How can I retain the anchor functionality and prevent #anchor being added to the url?

Cheers

Upvotes: 2

Views: 6703

Answers (4)

Damien
Damien

Reputation: 621

@DGibbs I took your code an modified it so that rather than having to write it out for each anchor on the page you can use this instead

$('.js-anchor').click(function (evt) {
        evt.preventDefault();
        var anchor = $(this).text();

        $('html, body').animate({
            scrollTop: $('#' + anchor).offset().top
        }, 1500);
    });

Maybe this will help someone else too. For reference the html looks like this

<a class="js-anchor">Top</a>


<span id="Top"></span>

Obviously with this code your anchor id must match the text inside the link for it to work

Upvotes: 0

Sina
Sina

Reputation: 775

It's up to you how you'd want to go about it, but I would do this:

<script type="text/javascript">

$(window).on('hashchange', function(e){ // listen if hashtag is being added to the URL

    location.href = location.href.replace(location.hash,"") //replace it with nothing
    console.log("bam!"); //enjoy it

});

</script>

Upvotes: 0

Charlie
Charlie

Reputation: 23768

Add click event listener to your links and use preventDefault.

$('.mylink').click(function(event){
    event.preventDefault();
});

This will stop the links from modifying the urls.

Upvotes: -1

DGibbs
DGibbs

Reputation: 14608

You could use scrollTop to achieve the same effect:

$('.js-hook--page-down').click(function (e) {
    e.preventDefault();

    $('html, body').animate({
        scrollTop: $("#anchor").offset().top - 200
    }, 1500);
});

And the HTML:

<a class="js-hook--page-down">page down</a>

<span id="anchor"></span>

You need a new js hook for each of the page anchors though.

Upvotes: 7

Related Questions