📜 ⬆️ ⬇️

Smooth scrolling when navigating anchors inside the page

Problem

When navigating on one-page sites, organized using anchors (a [name = target]), as well as surfing long documents with content linked to sections of the page, there is a problem of ease of use: the transition occurs instantly, the user does not always see where it has been transferred and what should focus on. Demo .

An attentive reader will undoubtedly recall that it has long been invented before us, for example, here . However, the govnod I sketched for half an hour is at least two times smaller in volume and does not require the search for any additional plug-ins.
')
Task

Make it so that the user clearly understands which part of the page he is throwing, draw attention to the goal of the transition.

Decision

We will use the power of jQuery. We intercept the transitions through the anchors and smoothly scroll the page to the goal of the transition, and after that a couple of times we blink an element that uniquely characterizes the purpose of the transition (or the goal itself, as it pleases).

When navigating from the outside, the target just winks, there is no need to turn the page. With internal transitions scroll and wink.

Page Layout (pseudocode)

ol class="toc"
a href="#1"
a href="#2"
a href="#3"
/ol

a name="1"
-
a name="2"
-
a name="3"
-


Javascript (jQuery enabled by default)

// HighLight target
$( document ).ready( function (){

// - .
var url = window.location;
var anchor = url.hash; //anchor with the # character
var anchor = url.hash.substring(1); //anchor without the # character

$( '[name=' + anchor + ']' ).next( 'h2' )
.fadeOut()
.fadeIn()
.fadeOut()
.fadeIn();

// .
$( '.toc a' ).click( function (){
var url = this ;
var anchor = url.hash; //anchor with the # character
var anchor = url.hash.substring(1); //anchor without the # character

// - , -.
// , body.
if (! $.browser.opera ) {
var targetOffset = $( 'a[name=' + anchor + ']' ).offset().top;
$( 'html,body' ).animate({scrollTop: targetOffset}, 1500);
} else {
var targetOffset = $( 'a[name=' + anchor + ']' ).next( 'h2' ).offset().top;
$( 'html' ).animate({scrollTop: targetOffset}, 1500);
} // if!opera

// .
$( '[name=' + anchor + ']' ).next( 'h2' )
.fadeOut()
.fadeIn()
.fadeOut()
.fadeIn()
.fadeOut()
.fadeIn();

// .
return false ;

// - .
//window.location.replace(this.pathname + '#' + anchor);

}); // click
}); // document ready


* This source code was highlighted with Source Code Highlighter .


Demo

Source: https://habr.com/ru/post/109060/


All Articles