New to Kendo UI for jQuery? Download free 30-day trial

Refocus the NumericTextBox after Switching to a Different Browser Tab

Environment

Product NumericTextBox for Progress® Kendo UI®

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

  1. Attach the focusin JavaScript event to the input elements and save the last focused element.
  2. Add an event listener to the visibilitychange JavaScript event.
  3. Check if the last focused element before switching the tab was a Kendo UI NumericTextBox.
  4. If the above condition is true, call the focus 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>
In this article
Not finding the help you need? Improve this article