Skip to content

Instantly share code, notes, and snippets.

@hakikz
Last active July 29, 2021 16:53
Show Gist options
  • Save hakikz/f83f90f7dca750a499f4ef8e4f34a17e to your computer and use it in GitHub Desktop.
Save hakikz/f83f90f7dca750a499f4ef8e4f34a17e to your computer and use it in GitHub Desktop.
Smooth Scroll
$('#return-to-top').click(function() { // When arrow is clicked
$('body,html').animate({
scrollTop : 0 // Scroll to top of body
}, 500);
});
// ===== Scroll to Top ====
$(window).scroll(function() {
if ($(this).scrollTop() >= 50) { // If page is scrolled more than 50px
$('#return-to-top').fadeIn(200); // Fade in the arrow
} else {
$('#return-to-top').fadeOut(200); // Else fade out the arrow
}
});
// SMOOTH SCROLLING TO ANCHORS
$('a[href*="#"]')
// Remove links that don't actually link to anything
.not('[href="#"]')
.click(function(event) {
// On-page links
if (
location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') &&
location.hostname == this.hostname
) {
// Figure out element to scroll to
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
// Does a scroll target exist?
if (target.length) {
// Only prevent default if animation is actually gonna happen
event.preventDefault();
$('html, body').animate({
scrollTop: target.offset().top
}, 1000, function() {
//<!-- Start Comment Callback after animation
// Must change focus! /End Comment-->
var $target = $(target);
$target.focus();
if ($target.is(":focus")) { // Checking if the target was focused
return false;
} else {
$target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
$target.focus(); // Set focus again
};
});
}
}
});
$('section').each(function () {
if($(this).position().top <= $(document).scrollTop() && ($(this).position().top + $(this).outerHeight()) > $(document).scrollTop()) {
console.log($(this).attr('class'));
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment