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
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
Share Improve this question asked Dec 9, 2015 at 9:36 DamienDamien 6211 gold badge7 silver badges18 bronze badges4 Answers
Reset to default 7You 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.
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>
@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
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.