/**
* Uses jQuery to creep to anchored text.
* @namespace creep
* @memberof UCASDesignFramework
* @param {object} jQuery - jQuery.
*/
;(function ($) {
'use strict';
UCASDesignFramework.creep = {
/**
* Initialise creep.
* @function init
* @memberof! UCASDesignFramework.creep
* @public
* @param {Node} context - DOM element we're limiting selection to
*/
init: function (context) {
// Click handler for same page anchors.
$('a[href^="#"]:not([href="#"]):not([class])', context).on('click', function (e) {
var id = $(this).attr('href').replace('#', '');
var element = $('#' + id).removeAttr('id');
// Remove target identifier to avoid default jump to behaviour.
// NOTE This is probably the thing that breaks the :target selector.
location.hash = id;
element.attr('id', id);
UCASDesignFramework.creep.creepTo(id);
e.preventDefault();
});
// Stop links with just # from jumping to the top.
$('a[href="#"]', context).on('click', function(e) {
e.preventDefault();
});
},
/**
* Creep to an anchor.
* @function creepTo
* @memberof! UCASDesignFramework.creep
* @public
* @param {string} id - name of anchor we're creeeping to
*/
creepTo: function (id) {
// If id starts with a forward slash, assume its a SPA route and ignore.
if (id.lastIndexOf('/', 0) === 0) {
return;
}
var destination = $("a[name='" + id + "']");
// If that didn't work, look for an element with our ID
if (!destination.length) {
destination = $('#' + id);
}
// If the destination element exists
if (destination.length) {
// Do the scroll.
setTimeout(function () {
var stickyNavHeight = $('[data-sticky-nav-container-fixed="true"]').height() || 0
$('html, body').animate({
scrollTop: destination.offset().top - stickyNavHeight - 10
}, 500);
}, 20);
}
}
};
})(jQuery);