Fixed position breaks on header when I click on the \"Search Form\" text box field. It simply detaches from the top of the page (as it\'s fixed up there) and starts floating
All of the solutions that I've tried so far failed one scenario for me: the fixed top navbar would disappear as soon as the keyboard is displayed on an iPhone. What if you want the fixed element to stay fixed in the same position even when the keyboard is displayed? Below is a simple solution that allows this, with a bonus of keeping the fixed element stuck to the top as you scroll the page while the keyboard is visible (i.e., with the focus still inside the input field).
// Let's assume the fixed top navbar has id="navbar"
// Cache the fixed element
var $navbar = $('#navbar');
function fixFixedPosition() {
$navbar.css({
position: 'absolute',
top: document.body.scrollTop + 'px'
});
}
function resetFixedPosition() {
$navbar.css({
position: 'fixed',
top: ''
});
$(document).off('scroll', updateScrollTop);
}
function updateScrollTop() {
$navbar.css('top', document.body.scrollTop + 'px');
}
$('input, textarea, [contenteditable=true]').on({
focus: function() {
// NOTE: The delay is required.
setTimeout(fixFixedPosition, 100);
// Keep the fixed element absolutely positioned at the top
// when the keyboard is visible
$(document).scroll(updateScrollTop);
},
blur: resetFixedPosition
});
To see a demo, go here on your iPhone:
http://s.codepen.io/thdoan/debug/JWYQeN/gakeYJYOXDPk
Here's a version using requestAnimationFrame
, but it didn't appear to perform any better, so I stuck with the first version since it's simpler:
http://s.codepen.io/thdoan/debug/VpvJNX/yYMyLDLBwpRk