Created
October 23, 2017 20:35
-
-
Save Andy-set-studio/ffeb1a91a13944e2001820eaf6d7e715 to your computer and use it in GitHub Desktop.
[jQuery Jump module] Used for creating a smooth transition for anchor links etc. Will automatically look for bindable elements on 'DOMNodeInserted DOMNodeRemoved' events for ajax content insertions etc. Also utilises history API. #jQuery #legacyJSToRefactor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function ($) { | |
$.fn.jump = function (options) { | |
var elem = $(this), | |
settings = { | |
scrollingParent: $('html, body'), | |
offsetPadding: 0, | |
scrollSpeed: 800, | |
target: [] | |
}; | |
// Main method | |
var init = function () { | |
// extend settings | |
settings = $.extend(true, {}, settings, options); | |
// if the trigger has already been bound, return out | |
if (elem.hasClass('is-bound')) { | |
return; | |
}; | |
// Store the target | |
settings.target = $(elem.attr('href')); | |
// If no target, return out | |
if (settings.target.length < 1) { | |
return; | |
} | |
else { | |
// If there is some offset padding for the element, override the setting | |
if (settings.target.attr('data-offset-padding')) { | |
settings.offsetPadding = parseInt(settings.target.attr('data-offset-padding')); | |
} | |
// Add the bound class to the trigger | |
elem.addClass('is-bound'); | |
// If the window's current hash is this href, jump! | |
if (window.location.hash == elem.attr('href')) { | |
jump(); | |
} | |
} | |
// Bind click event | |
elem.off('click').on('click', function (evt) { | |
// If pushstate is supported | |
if (window.history && window.history.pushState) { | |
// prevent default event (stops blinkyness) | |
evt.preventDefault(); | |
// Push the hash | |
history.pushState(null, null, elem.attr('href')); | |
} | |
// 'Jump... For my love' | |
jump(); | |
}); | |
return elem; | |
}, | |
// Jump method | |
jump = function () { | |
// check the target again | |
if (settings.target.length > 0) { | |
// Scrolly scroll time | |
$(settings.scrollingParent).animate({ | |
scrollTop: settings.target.offset().top - settings.offsetPadding | |
}, settings.scrollSpeed); | |
} | |
}; | |
// Fire main method | |
init(); | |
return this; | |
}; | |
}($)); | |
// Bind to all the elements!! | |
var bindJump = function () { | |
$('.js-jump').each(function () { | |
$(this).jump(); | |
}); | |
}; | |
$(document).ready(function () { | |
// Fire global bind | |
bindJump(); | |
// When new elements added to dom (ajax etc) run bind again | |
$('body').on('DOMNodeInserted DOMNodeRemoved', function () { | |
bindJump(); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment