Search code examples
safarimobile-safari

iOS iPad Fixed position breaks when keyboard is opened


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 middle of the page when the virtual keyboard opens up.

Normal:

enter image description here

Broken:

enter image description here


Solution

  • I really like this solution (http://dansajin.com/2012/12/07/fix-position-fixed/). I packaged it up into a little jQuery plugin so I could:

    • Set which parent gets the class
    • Set which elements this applies to (don't forget "textarea" and "select").
    • Set what the parent class name is
    • Allow it to be chained
    • Allow it to be used multiple times

    Code example:

    $.fn.mobileFix = function (options) {
        var $parent = $(this),
    
        $(document)
        .on('focus', options.inputElements, function(e) {
            $parent.addClass(options.addClass);
        })
        .on('blur', options.inputElements, function(e) {
            $parent.removeClass(options.addClass);
    
            // Fix for some scenarios where you need to start scrolling
            setTimeout(function() {
                $(document).scrollTop($(document).scrollTop())
            }, 1);
        });
    
        return this; // Allowing chaining
    };
    
    // Only on touch devices
    if (Modernizr.touch) {
        $("body").mobileFix({ // Pass parent to apply to
            inputElements: "input,textarea,select", // Pass activation child elements
            addClass: "fixfixed" // Pass class name
        });
    }
    

    EDIT: Removed unnecessary element