On loading a page I would like it to go to #content
without changing the url.
I thought I would be able to use
window.location.hash = "content";
window.location.replace("#content", "");
but #content
still exists on the url.
Any better method?
Edit:
Also tried
window.location.hash = "content";
window.location.replace(window.location.toString().replace("#content", ""));
But this sends the browser into a loop.
You could find the vertical position of the anchor with that id, and then scroll to that position.
This is a 10 year old question but I came across this issue when using Nextjs and wanted to smoothly navigate to a lower element without effecting the url... Nextjs, Typescript.
const Anchor: React.FC = () => {
const smoothScrollTo = e => {
e.preventDefault();
const element = document.getElementById('search');
element.scrollIntoView({
block: 'start',
behavior: 'smooth' // smooth scroll
})
};
return (
<div>
<a
href=""
onClick={smoothScrollTo}>
Let's go!
</a>
<div id = "search">Take me here!</div>
</div>
)
};
Now, it would probably be a best practice to be using refs here but this did exactly what I needed! I'm sure other improvements can be made too!
Go to or Scroll to anchor specified div id without changing url
TRY DEMO
function scrollSmoothTo(elementId) {
var element = document.getElementById(elementId);
element.scrollIntoView({
block: 'start',
behavior: 'smooth'
});
}
#userdiv {
margin-top: 200px;
width: 200px;
height: 400px;
border: 1px solid red;
}
a {
color: #337ab7;
cursor: pointer;
}
a:hover {
text-decoration: underline;
}
<a onclick="scrollSmoothTo('userdiv')">
Scroll to userdiv
</a>
<div id="userdiv">
Lorem ipsum this is a random text
</div>
This will do it with a nice animation:
<a href="#link">Click to scroll</a>
<div id="link" style="margin-top: 1000px; height: 300px; background-color: blue; margin-bottom: 1000px">
Click and scroll to this div without changing url!
</div>
<script>
$('a').on('click', function(e) {
// prevent default anchor click behavior
e.preventDefault();
// store hash
var hash = this.hash;
if ($(hash).length) {
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 300, function() {
// Do something fun if you want!
});
}
});
</script>
Working JSFiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With