JavaScript - markhowellsmead/helpers GitHub Wiki

Share link window size/position

Hash Scroll

Thanks https://css-tricks.com/snippets/jquery/smooth-scrolling/

(function(namespace) { // Closure to protect local variable "var hash"
	if ('replaceState' in history) { // Yay, supported!
		namespace.replaceHash = function(newhash) {
			if (('' + newhash).charAt(0) !== '#') {
				newhash = '#' + newhash;
			}
			history.replaceState('', '', newhash);
		};
	} else {
		var hash = location.hash;
		namespace.replaceHash = function(newhash) {
			if (location.hash !== hash) {
				history.back();
			}
			location.hash = newhash;
		};
	}
})(window);


(function($) {

	var goThere, thisHash;

	var scrollTo = function($target) {
		if ($('body').hasClass('admin-bar')) {
			goThere = $target.offset().top - $('#wpadminbar').outerHeight();
		} else {
			goThere = $target.offset().top;
		}

		goThere -= $('.navbar-default').outerHeight();

		window.replaceHash(thisHash);

		$('html, body').animate({
			scrollTop: goThere
		}, 600, function() {
			// Callback if you need to do something after the scrolling is complete
		});
	};

	$('a[href*="#"]')
		// Remove links that don't actually link to anything
		.not('[href="#"]')
		.not('[href="#0"]')
		.on('click.hashscroll', function(event) {

			// On-page links
			if (
				location.pathname.replace(/^\//, '') === this.pathname.replace(/^\//, '') &&
				location.hostname === this.hostname
			) {
				// Figure out element to scroll to
				var $target = $(this.hash);

				$target = $target.length ? $target : $('[name=' + this.hash.slice(1) + ']');
				// Does a scroll $target exist?
				if ($target.length) {
					// Only prevent default if animation is actually gonna happen
					event.preventDefault();
					thisHash = this.hash;
					scrollTo($target);
				}
			}
		});

	$(window).on('load.checkHash', function() {
		if (window.location.hash && window.location.hash !== '') {
			if ($('[data-anchorID="' + window.location.hash.replace('#', '') + '"').length) {
				scrollTo($('[data-anchorID="' + window.location.hash.replace('#', '') + '"'));
			}
		}
	});
}(jQuery));

Back to top (animated)

(function($) {

  $(document).on('ready.backtotop', function() {
    if ($('[data-pagetop-anchor]').length === 1) {
      $('[data-pagetop-link]').on('click.backtotop', function(event) {
        event.preventDefault();
        $("html, body").animate({
          scrollTop: $('[data-pagetop-anchor]').offset().top
        }, 300, 'swing');
      });
    }
  });

}(jQuery));

Single functions

See https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams for getting/managing URL parameters if no IE11 support is needed.

function getUrlParameter(sParam) {
    // Thanks http://www.jquerybyexample.net/2012/06/get-url-parameters-using-jquery.html
    var sPageURL = decodeURIComponent(window.location.search.substring(1)),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : sParameterName[1];
        }
    }
};
var isValidJson = function( raw_json ) {
	try {
		var json = $.parseJSON( raw_json );
		return ( json && 'object' === typeof json );
	} catch ( e ) {
		return false;
	}
};
$.extend( $.fn, {
    matchHeights: function() {
        var $_that = $(this);
        var heights = $_that.map(function() {
                console.log($(this).height());
                return $(this).height();
            }).get(),
            maxHeight = Math.max.apply(null, heights);
        $_that.height(maxHeight);
        return this;
    }
});
$.fn.isInViewport = function() {
	var elementTop = $(this).offset().top;
	var elementBottom = elementTop + $(this).outerHeight() - 100;
	var viewportTop = $(window).scrollTop();
	var viewportBottom = viewportTop + $(window).height();
	return elementBottom > viewportTop && elementTop < viewportBottom;
};
var watchElementArrival = function() {
	$('[data-watch-arrival]').each(function() {
		if ($(this).isInViewport()) {
			$(this).addClass('is--inviewport');
		}
	});
};

Watch scroll position

window.addEventListener('scroll', function() {
	if (window.scrollY > 0) {
		document.body.classList.add('is--scrolled');
	} else {
		document.body.classList.remove('is--scrolled');
	}
});