Created
October 6, 2014 19:32
-
-
Save dwtkns/96dcbbb05a5b50ed736b to your computer and use it in GitHub Desktop.
Lock viewport onto an element during resize
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
// Looks an element up by CSS selector and keeps it centered in the viewport on window resize | |
// Useful for testing responsive versions of specific DOM elements | |
// if jquery isn't loaded on the page, paste this code into the console first to load it: | |
var jqURL = 'http://code.jquery.com/jquery-latest.min.js'; | |
var jqscript = document.createElement('script'); | |
jqscript.type= 'text/javascript'; | |
jqscript.src = jqURL; | |
document.head.appendChild(jqscript); | |
// ------ Paste the code below into your console to lock the viewport onto a given element | |
// Change the string below to match the element you want to lock in the center of your view | |
var target = '#targetElementIdGoesHere'; | |
// bind event to center the target id in the viewport any time the window is resized | |
$( window ).resize(function() { | |
var top = $(target).offset().top, | |
height = $(target).outerHeight(true), | |
windowHeight = $(window).height(); | |
$('html,body').scrollTop(top - ( windowHeight - height )/2 ); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment