Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting Click outside a text field

I have a submit button and a text field. I know how to detect when user clicks inside the text field. Basically what i am doing is, when user clicks inside the text field, hide the text.

if (submitTextArea.addEventListener) {
  submitTextArea.addEventListener("click", function() {
    if (submitTextArea.value == 'Enter First Name') { //Customize this text string to whatever you want
      submitTextArea.value = '';
    }
  });
}

Now when user clicks away from the text field, that is in some other area out side the text field i want to restore the text.

How can i detect the click outside text field?

like image 460
donguy76 Avatar asked Mar 19 '15 21:03

donguy76


1 Answers

What you looking for is a blur event.

submitTextArea.addEventListener("blur", function() {
  // code here
});

Here you have a entire page of JavaScript events with supported browsers : http://www.quirksmode.org/dom/events/


Also it would be better if you use focus and blur events for this task, so that click event may be used for another action.

Working fiddle: http://jsfiddle.net/urahara/6nspgrj4/2/

Code:

submitTextArea.addEventListener("focus", function () {
    submitTextArea.value = 'Got focus';
});

submitTextArea.addEventListener("blur", function () {
    submitTextArea.value = 'Lost focus';
});    
like image 145
Piotr Dajlido Avatar answered Oct 21 '22 07:10

Piotr Dajlido