Skip to content

Instantly share code, notes, and snippets.

@dwtkns
Created October 6, 2014 19:32
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dwtkns/96dcbbb05a5b50ed736b to your computer and use it in GitHub Desktop.
Save dwtkns/96dcbbb05a5b50ed736b to your computer and use it in GitHub Desktop.
Lock viewport onto an element during resize
// 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