From 8d5e7e70abfc8b8db2487eced70f3317da9e1aef Mon Sep 17 00:00:00 2001 From: Tom Byers Date: Thu, 28 Mar 2019 16:45:36 +0000 Subject: [PATCH] Prevent autofocus when page has scrolled If users scroll a page with an autofocus component on so it is off-screen it seems safe to assume they won't want it focused if they return to it. This prevents that happening. This adds a data-attribute flag to allow this behaviour to be overridden. We have some situations where the assumption here isn't appropriate, for example on pages where the component with autofocus is in a sticky element. This means it will appear offscreen when the page loads but, when its parent becomes sticky, will be visible again. --- app/assets/javascripts/autofocus.js | 9 +++++++-- app/templates/views/send-test.html | 3 ++- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/app/assets/javascripts/autofocus.js b/app/assets/javascripts/autofocus.js index 2d276953f..299914e4b 100644 --- a/app/assets/javascripts/autofocus.js +++ b/app/assets/javascripts/autofocus.js @@ -2,9 +2,14 @@ "use strict"; Modules.Autofocus = function() { - this.start = function(component) { + this.start = function($component) { + var forceFocus = $component.data('forceFocus'); - $('input, textarea, select', component).eq(0).trigger('focus'); + // if the page loads with a scroll position, we can't assume the item to focus onload + // is still where users intend to start + if (($(window).scrollTop() > 0) && !forceFocus) { return; } + + $('input, textarea, select', $component).eq(0).trigger('focus'); }; }; diff --git a/app/templates/views/send-test.html b/app/templates/views/send-test.html index c84c5fbce..967f72a08 100644 --- a/app/templates/views/send-test.html +++ b/app/templates/views/send-test.html @@ -16,7 +16,8 @@ {% call form_wrapper( class='js-stick-at-top-when-scrolling send-one-off-form' if template.template_type != 'sms' else 'send-one-off-form', - module="autofocus" + module="autofocus", + data_kwargs={'forceFocus': True} ) %}