Refocus the NumericTextBox after Switching to a Different Browser Tab
Environment
Product | Progress® Kendo UI® NumericTextBox for jQuery |
Description
I have focused a NumericTextBox input but after switching to a different browser tab and coming back to the page containing the NumericTextBox, the focus is lost. How can I prevent the Kendo UI NumericTextBox from losing its focus when I switch to a different tab?
Solution
- Attach the
focusin
JavaScript event to the input elements and save the last focused element. - Add an event listener to the
visibilitychange
JavaScript event. - Check if the last focused element before switching the tab was a Kendo UI NumericTextBox.
- If the above condition is
true
, call thefocus
method of the NumericTextBox.
<input id="numeric" />
</br>
</br>
<input id="numeric2" />
<script>
window.prevActiveElement = $();
$(document).on('focusin', 'input', function () {
window.prevActiveElement = $(this);
});
document.addEventListener("visibilitychange", function(e) {
let tabActive = document.visibilityState === "visible";
let prevElementWasNumeric = window.prevActiveElement.is($("[data-role='numerictextbox']"));
if(tabActive && prevElementWasNumeric) {
window.prevActiveElement.data("kendoNumericTextBox").focus();
}
});
$("#numeric").kendoNumericTextBox();
$("#numeric2").kendoNumericTextBox();
</script>