Search code examples
javascriptajaxfocusform-submit

Knowing focused element id before form submit


I want to return focus to the html element (that fires submit of my form) after ajax checkings. because always my form is submitted the last focused element is always the submit button.

How can i know the previous elemnt that had the focus (in pure JS please)?

Thanks in advance


Solution

  • To return focus to the HTML element that fires submit of your form after AJAX checkings, you can use the focus() method in JavaScript. You can store the previous element that had the focus in a variable before the AJAX call and then use it to set the focus back to that element after the AJAX call.

    Example:

    // Store the previously focused element
    let previousElement = document.activeElement;
    
    // Perform AJAX call
    $.ajax({
      url: "your-url",
      success: function() {
        // Set focus back to the previously focused element
        previousElement.focus();
      }
    });
    

    To get the previously focused element in pure JavaScript, you can use the document.activeElement property. This property returns the currently focused element in the document. You can store this value in a variable before the AJAX call and then use it to set the focus back to that element after the AJAX call.

    // Store the previously focused element
    let previousElement = document.activeElement;
    
    // Perform AJAX call
    let xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
      if (xhr.readyState === 4 && xhr.status === 200) {
        // Set focus back to the previously focused element
        previousElement.focus();
      }
    };
    xhr.open("GET", "your-url", true);
    xhr.send();