Last active
January 3, 2016 03:39
-
-
Save astromac/8403689 to your computer and use it in GitHub Desktop.
Scrolls form inputs when they are hidden by a fixed header or footer
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
// Make sure focused elements aren't hidden by fixed positioned header or footer | |
function unhideInput(formelement) { | |
formelement.onfocus = function () { | |
var paddingheight = 30; | |
var headerheight = document.getElementsByTagName('header')[0].offsetHeight; | |
var footerheight = document.getElementsByTagName('footer')[document.getElementsByTagName('footer').length - 1].offsetHeight; | |
var viewportheight = window.innerHeight; | |
var elementpos = this.getBoundingClientRect(); | |
if ((elementpos.top <= (headerheight + paddingheight)) || (elementpos.bottom >= (viewportheight - footerheight))) { | |
this.scrollIntoView(true); | |
window.scrollBy(0, Math.round(viewportheight / 2)); | |
} | |
} | |
} | |
var htmltag = document.getElementsByTagName('html')[0]; | |
if (! /iOS/i.test(htmltag.className)) { | |
var forminputs = document.getElementsByTagName('input'); | |
var formtextareas = document.getElementsByTagName('textarea'); | |
var formbuttons = document.getElementsByTagName('button'); | |
for (var i = forminputs.length - 1; i >= 0; i--) { | |
forminputs[i].addEventListener('focus', unhideInput(forminputs[i]), false); | |
}; | |
for (var i = formtextareas.length - 1; i >= 0; i--) { | |
formtextareas[i].addEventListener('focus', unhideInput(formtextareas[i]), false); | |
}; | |
for (var i = formbuttons.length - 1; i >= 0; i--) { | |
formbuttons[i].addEventListener('focus', unhideInput(formbuttons[i]), false); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment