Skip to content

Instantly share code, notes, and snippets.

@brantwedel
Last active August 29, 2015 13:57
Show Gist options
  • Save brantwedel/9907932 to your computer and use it in GitHub Desktop.
Save brantwedel/9907932 to your computer and use it in GitHub Desktop.
Detect keyboard in PhoneGap/HTML5 app to modify UI and keep text input in view
setInterval ->
return if $("#footer-region").length == 0
window.last_width |= 0
window.last_height |= 0
width = $("#footer-region").width()
height = $("#footer-region").offset().top + $("#footer-region").height()
unless window.active_input_listeners
window.active_input_listeners = true
focusCheck = (event) ->
if event.target.tagName == "TEXTAREA" || event.target.tagName == "INPUT"
window.active_input = event.target
return if $("#footer-region").height() < 10
$("#footer-region").css(pointerEvents: "none")
# on ipad element must be in view after keyboard appears to properly gain focus, fix it here!
if document.activeElement != window.active_input
if $(window.active_input).closest(".scroll-container").length > 0
scroll = $(window.active_input).closest(".scroll-container").scrollTop()
offset = $(window.active_input).closest(".scroll-container").offset().top
top = $(window.active_input).offset().top
if $(window.active_input).closest(".scroll-container").scrollTop() < scroll + top - 60
$(window.active_input).closest(".scroll-container").scrollTop(scroll + top - 60)
event.gesture.preventDefault() if event.gesture
$(window.active_input).focus() # focus can only be called during a user initiaited event
clearTimeout(window.active_input_timeout) if window.active_input_timeout
window.active_input_timeout = setTimeout ->
$("#footer-region").css(pointerEvents: "default")
, 400
$("body").hammer().on "tap", focusCheck
try
if $(window.active_input).closest(".scroll-container").length > 0
scroll = $(window.active_input).closest(".scroll-container").scrollTop()
offset = $(window.active_input).closest(".scroll-container").offset().top
top = $(window.active_input).offset().top
catch ee
if width != window.last_width
window.last_height = 0
window.last_width = width
if window.last_height != height
if window.last_height > height
$("#footer-region").css(height: "0px")
try
if $(window.active_input).closest(".scroll-container").length > 0
if $(window.active_input).closest(".scroll-container").scrollTop() < scroll + top - 60
$(window.active_input).closest(".scroll-container").scrollTop(scroll + top - 60)
catch ee
else
$("#footer-region").css(height: "60px")
window.last_height = height
, 50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment