Created
October 25, 2016 12:37
-
-
Save williankeller/cd6ad62bdb221444d4b4e720f07d7ae7 to your computer and use it in GitHub Desktop.
GoTo global function
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 ($) { | |
| "use strict"; | |
| var opt = { | |
| // Area to detect click ation | |
| onClickArea: document, | |
| // Attribute to get the click ation | |
| attribute: '.goto a', | |
| // Incremental space difference to top | |
| spaceToTop: 20, | |
| // Animation time | |
| animationTime: 'slow', | |
| // Block action on mouse click | |
| preventClick: true, | |
| // Change hash URL on header | |
| headerUrl: true, | |
| // Auto go to on page load | |
| liveAnchor: true | |
| }; | |
| /** | |
| * Function to go on attribute ID | |
| * @param {string} target | |
| * @returns {false} | |
| */ | |
| var actionGoTo = function (target) { | |
| if ($(target).offset() !== null) { | |
| // Start animation scroll | |
| $('html, body').animate({ | |
| scrollTop: ($(target).offset().top - opt.spaceToTop) | |
| }, opt.animationTime); | |
| } | |
| return false; | |
| }; | |
| /** | |
| * Onclick detection | |
| * Get the click in destionation attribute | |
| */ | |
| $(opt.onClickArea).on('click', opt.attribute, function (e) { | |
| // Instance achor attribute | |
| var $anchorHash = $(this).attr('href'); | |
| // Function GoTo | |
| actionGoTo($anchorHash); | |
| // Check header URL change | |
| if (opt.headerUrl === true) { | |
| // Get current hash | |
| window.location.hash = $anchorHash; | |
| } | |
| // Check prevent click ation | |
| if (opt.preventClick === true) { | |
| e.preventDefault(); | |
| } | |
| }); | |
| // Check auto scroll on page load | |
| if (opt.liveAnchor === true) { | |
| // Start document | |
| $(document).ready(function () { | |
| // Instance hash anchor | |
| var anchorHash = window.location.hash; | |
| // Check if is a valid anchor | |
| if ((anchorHash !== undefined) && (anchorHash[0] === '#')) { | |
| // Function GoTo | |
| actionGoTo(anchorHash); | |
| } | |
| }); | |
| } | |
| })(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment