anchor.js

Jump to a specific section smoothly

by NunoMira

HTML

<body>
    <h1>anchor.js</h1>
    <section id="section1">
        <h3>This is the first section</h3>
        <p><a href="#section2">Jump to next section</a></p>
    </section>
    <section id="section2">
        <h3>You are at Section 2 now</h3>
        <p><a href="#section3">Jump to next section</a></p>
    </section>
    <section id="section3">
        <h3>You are at Section 3 now</h3>
        <p><a href="#section1">Jump to first section</a></p>
        </section>
</body>

CSS

[id^=section] {
    margin-bottom: 100%;
}

JavaScript

//Anchoragem dentro de uma página com animação (mais facil de usar)
$(function() {
    $('a[href*=#]').anchor({
        transitionDuration : 1200
    });
});

/**
 * anchor.js - jQuery Plugin
 * Jump to a specific section smoothly
 *
 * @dependencies	jQuery v1.5.0 http://jquery.com
 * @author			Cornel Boppart <[email protected]>
 * @copyright		Author
 
 * @version		1.0.5 (02/11/2014)
 */

;(function ($) {
	
	window.anchor = {
		
		/**
		 * Default settings
		 *
		 */
		settings: {
			transitionDuration: 2000,
			transitionTimingFunction: 'swing',
			labels: {
				error: 'Couldn\'t find any section'
			}
		},

		/**
		 * Initializes the plugin
		 *
		 * @param	{object}	options	The plugin options (Merged with default settings)
		 * @return	{object}	this	The current element itself
		 */
		init: function (options) {
			// Apply merged settings to the current object
			$(this).data('settings', $.extend(anchor.settings, options));

			return this.each(function () {
				var $this = $(this);

				$this.unbind('click').click(function (event) {
					event.preventDefault();
					anchor.jumpTo(
						anchor.getTopOffsetPosition($this),
						$this.data('settings')
					);
				});
			});
		},

		/**
		 * Gets the top offset position
		 *
		 * @param	{object}	$object				The root object to get sections position from
		 * @return	{int}		topOffsetPosition	The top offset position
		 */
		getTopOffsetPosition: function ($object) {
			var href = $object.attr('href'),
				$section = $($(href).get(0)),
				documentHeight = $(document).height(),
				browserHeight = $(window).height();

			if (!$section || $section.length < 1) {
				throw new ReferenceError(anchor.settings.labels.error);
			}

			if (($section.offset().top + browserHeight) > documentHeight) {
				return documentHeight - browserHeight;
			} else {
				return $section.offset().top;
			}
		},
		
		/**
		 * Jumps to the specific position
		 *
		 * @param	{int}		topOffsetPosition	The top offset position
		 *...