Dynamic jQuery Smooth Scroll to Anchor - javascript

I have a code snippet from the W3 schools that creates a smooth scroll function to anchor tags within a page. It does this dynamically by looking for anchors that have hashes in it, and I would like to keep it this way without having to add classes etc. The issue I'm experiencing is when the script appends the URL to include the anchor id, it breaks the top offset. How can I append this code to prevent that from happening?
$(document).ready(function(){
$("a").on('click', function(event) {
if (this.hash !== "") {
event.preventDefault();
var hash = this.hash;
$('html, body').animate({
scrollTop: $(hash).offset().top-125
}, 1000,
function(){
window.location.hash = hash;
});
}
});
});

Related

Disable Smooth Scrolling on Non-Anchor Hash Link?

I have some jquery for smooth scrolling:
$(document).on('click', 'a[href^="#"]', function (event) {
event.preventDefault();
$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top
}, 1400);
});
Which works fine, except that I have some tabs on the page that use a hash link also. When you click each tab, the page scrolls to the top of the screen.
Is there a way to make this smooth scroll work, only when a specific anchor is added to the hash (like /#features) and not work when it is a hash only (like /#)
You can add a :not() selector to eliminate href="#" from triggering your click event.
$(document).on('click', 'a[href^="#"]:not([href=#])', function(event) {
console.log("Clicked");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Hash Only
Anchor 1
Anchor 2

Difference between onclick() and .on('click',function())? [duplicate]

This question already has answers here:
Difference between .on('click') vs .click()
(12 answers)
Closed 5 years ago.
$(document).ready(function(){
// Add smooth scrolling
$('.button').children().onclick(function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 1000, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
$(document).ready(function(){
// Add smooth scrolling to all links
$('.button').children().on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 1000, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
When i use onclick() function, on clicking the button there is no scrolling effect; it only jumps to article without any scrolling effect.
But when I use on('click',function()) there is a scrolling effect.
what is the difference between these two?
.onclick() is a javascript function
.click() and .on("click") are jQuery functions, and jQuery added some more features to its functions.

Removing smooth scroll from tabs

I have smooth scroll JS to link from a menu item to an anchor further down the page.
The problem is that since I have tabs used on my page (which use #tabname) to navigate, it tries to scroll when using them as well.
Is there an easy change I can make to the JS to prevent this from working on tabs?
$(document).ready(function () {
// Add smooth scrolling to all links
$("a").on('click', function (event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function () {
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
You could provide a way for anchor elements to opt out of the scroll behaviour, e.g. filter out anchors with a data-no-scroll attribute:
<a href="#tab1" data-no-scroll>Tab1</a>
$("a").not("[data-no-scroll]").click(function() {
...
});

Variable not passed into jQuery scroll function

Can someone help me understand why this is not working:
jQuery(".page-code .opening .button").click(function(event){
event.preventDefault();
var id = "#" + event.target.id;
alert(id);
jQuery('html, body').animate({
scrollTop: jQuery(id).offset().top
}, 500);
})
The anchor links exist in various parts of the page, the alert is giving me proper id that I need, but the page is only scrolling a tiny bit no matter which button I click. Not sure what I'm missing here.
You're setting up the destination of the scroll to be the element that was just clicked. If you want to scroll to the element that the link points to, you need to use the href attribute (assuming your buttons are a tags):
jQuery(".page-code .opening .button").click(function(event){
event.preventDefault();
var id = "#" + jQuery(this).attr('href');
alert(id);
jQuery('html, body').animate({
scrollTop: jQuery('body').offset().top
}, 500);
})
If you would you like to do that user click to .page-code OR .opening OR .button elements then add comma to between them.

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,
page down
<span id="anchor"></span>
How can I retain the anchor functionality and prevent #anchor being added to the url?
Cheers
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.
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.

Categories