Astuces Web - Ancrage en douceur
Présentation
Si vous avez déjà utilisé des ancres sur une
section de votre page (<a href="#id">),
vous vous êtes peut-être retrouvé à penser
que l'accès «brutal» à la dite
section est assez moche (¬_¬“;)...
Du coup, je vais vous montrer brièvement comment changer cela
grâce au JavaScript et jQuery.
Fonctions JavaScript
Récupération du premier élément «scrollable» parmi la liste d'éléments passés à la fonction (arguments variables) :
/**
* Function to get the first scrollable element
*
* Function the get the first scrollable element among the arguments of the
* function.
*
* @author brunotm
*
* @param $ jQuery instance
* @param els dummy parameter
*/
function scrollableElement($, els) {
for (var i = 1, argLength = arguments.length; i < argLength; i++) {
var el = arguments[i], $scrollElement = $(el);
if ($scrollElement.scrollTop() > 0) {
return el;
}
else {
$scrollElement.scrollTop(1);
var isScrollable = $scrollElement.scrollTop() > 0;
$scrollElement.scrollTop(0);
if (isScrollable) {
return el;
}
}
}
return [];
};
Fonction pour aller à une portion donnée de la page
/**
* Function to smoothly scroll to an element of the page
*
* Once the animation is ended, the location hash will be replaced by the
* one that we moved to (in order to reproduce the default behavior).
*
* @author brunotm
*
* @param $ jQuery instance
* @param id Id of the element to scroll to
*/
function goToByScroll($, id, time){
$(scrollableElement($, 'html', 'body'))
.animate({scrollTop: $('#'+id).offset().top},
(time != null ? time : 800),
function () {
location.hash = '#'+id;
}
);
};
Et enfin, une fonction qui va parser votre page et remplacer les ancres
(#id) par une fonction JavaScript qui va
déplacer la scrollbar jusqu'à la section
recherchée :
/**
* Function to add a smmoth scrolling to every anchor in the page
*
* This function will parse the page, looking for every anchor on an existing
* section of the current page and replace the default behavior (goto section)
* by a 'smooth scrolling to section' animation.
*
* It is highly advised to launch this function when the page is LOADED (i.e.
* not ready), meaning: <body onload="javascript: autoSmoothScrolling(jQuery)">
*
* @author brunotm
*
* @param $ jQuery instance
*/
function autoSmoothScrolling($) {
$.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase());
$.browser.ipad = /ipad/.test(navigator.userAgent.toLowerCase());
var locationPath = getUrlPath();
// the ipad already smoothly scrolls and does not detect the scrollable
// element if top=0; as such we disable this behaviour for the iPad
if (!$.browser.ipad) {
// for each anchor in the page
$('a[href*=#]').each(function () {
var thisPath = filterPath(this.pathname) || locationPath;
// if anchor to the same page
if (locationPath == thisPath && (location.hostname == this.hostname || !this.hostname) && this.hash.replace(/#/, '')) {
var $target = $(this.hash), target = this.hash;
// if target exists
if ($target.length > 0) {
$(this).click(function (event) {
event.preventDefault(); // prevent the 'goto target' behavior
goToByScroll($, target.substr(1));
});
}
}
});
}
};
Je tiens à remercier Patate Aurélie
DHENRY pour m'avoir donné l'idée de cette évol'
(^_^)
