Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the previously focused element in JavaScript?

I have an HTML form with multiple text inputs. I want to clear the element that had the focus immediately prior to when the 'Clear' button is pressed. How do I get that element in JavaScript?

Note: Reworded to take comments into account.

like image 261
HashimR Avatar asked Sep 07 '11 05:09

HashimR


People also ask

How do you find the focus element?

Syntax: var ele = document. activeElement; Return value: It returns the currently focused element in the document.

How do you remove focus from current element?

The blur() method removes focus from an element.

How do you check input is focused or not?

To check if an input field has focus with JavaScript, we can use the document. activeElement property to get the element in focus. to add an input.

How do you know if an element is focused HTML?

The hasFocus() method returns a true if the document (or any element in the document) has focus. Otherwise it returns false .


2 Answers

Create a global variable for storing the current focused element's id,

var cur_id;

call one function for onblur of each of elements and pass id

<input type="text" id="name" name="name" onBlur="setId(this.id)">

and write the set the id to global variable from that function

function setId(id) {
    cur_id = id;
}

and write a function for onclick of clear button, like this

function clear() {
    document.getElementById(cur_id).value = "";
}
like image 165
laradev Avatar answered Oct 19 '22 05:10

laradev


When you click "clear" button, only element focused is "clear" button. You'll have to workaround it. (trigger onblur event)

like image 32
genesis Avatar answered Oct 19 '22 05:10

genesis