I'd like to make a auto scroll to focus function for mobile users, so they won't have trouble with the keyboard anymore which is sometimes overlapping the inputs.
->If someone clicks on a input the page scrolls down to this, -64px because of fixed navigation.
My problem is if for example a tablet user change view from landscape to portrait the function could not work because I set up:
if ($( window ).width() <= 1250) {});
So I made a call function like that:
$(window).resize(function() {
resizeFix();
});
But the problem is it loops infinite times after changed window width.
The whole code:
$(document).ready(function(){
resizeFix = function() {
if ($( window ).width() <= 1250) {
$('input[type=text], input[type=checkbox], input[type=password], textarea').focus(function() {
$('html, body').animate({
scrollTop: $('input:focus, textarea:focus').offset().top - 64
}, 500);
});
};
};
resizeFix();
$(window).resize(function() {
resizeFix();
});
});
EDIT: I already tried:
$(window).resize(function() {
if ($( window ).width() <= 1250) {
resizeFix();
});
});
This happens because on each resize event you are attaching a new event listener for focus per element. You only ever want one. So keep track of it with a boolean, for instance. (What you're actually doing is keeping track whether the function resizeFix has been triggered already or not.) To make sure that the listener does not trigger again when you re-scale to > 1250, you can then call off()
.
$(document).ready(function() {
var listenerAttached = false;
var resizeFix = function() {
var w = $(window).width();
if (!listenerAttached && w <= 1250) {
$('input[type=text], input[type=checkbox], input[type=password], textarea').on("focus", function() {
$('html, body').animate({
scrollTop: $('input:focus, textarea:focus').offset().top - 64
}, 500);
});
listenerAttached = true;
} else if (listenerAttached && w > 1250) {
$('input[type=text], input[type=checkbox], input[type=password], textarea').off("focus");
listenerAttached = false;
}
};
resizeFix();
$(window).resize(function() {
resizeFix();
});
});