Search code examples
javascriptjqueryeventhandlerstoppropagation

How to add an EventListener that listens every click on window besides a specific element


I have a simple html file that has only one input field:

<input value="Hello">

What I want is that the moment the user clicks on the input field, he/she will be able to edit the text, and then once the finish the edit and click somewhere else (not inside the text field) in the window, the user will get an alert with the new input.

My JS code is:

$('document').ready(function(){
   $($('input')[0]).click(function() {
      alert('OK1');
      $(this).addClass('input-edit');
      $($(window)[0]).click(function() {
         alert('OK2');
         var text = $('input').value;
         alert(text);
      });
      $($('input')[0]).click(function(e) {
         e.stopPropagation();
         return false;
      });
   })
}) 

However, when I run the code, I see that the moment I click the first time inside the text field, the code behaves like it automatically got two clicks, so I get 3 alerts:

OK1 OK2 undefined

Do you know what I can do to ensure that the second click behave as I expect?


Solution

  • I think you are missing the blur event. The event when an element loses focus (or cursor in this case) is called blur event. You just need to add an event handler to blur event of your input element. Try

    $('input').blur(function(e) {
        alert($(this).val());
    }
    

    Since you have only one input element, getting the 0-indexed element is not required.