Execute function when losing focus of an input

Asked

Viewed 6,855 times

4

I have a normal html input:

<input type="text" class="form-control" style=" width: 20%" id="hLane1"> </input>

To make it run an event just use the event click

But what if I need to perform another action when the user clicks off the input?

I need that when the selection leaves that imput a function is executed.

4 answers

7

The very one Javascript has the function onblur performing a particular action or function when the input lose focus (be clicked out):

function teste(){
  console.log('teste')
}
<input onblur="teste()">

5


You can use the event onblur that is triggered when an element loses focus, see the example below:

let el = document.getElementById("hLane1");

el.onblur = function(){
   console.log("blur", "saiu do input" , this);
   /// ; utilizando desta forma o this aqui dentro sera o input
}
el.onfocus = function(){
   console.log("focus", "focou no input");
}
<input type="text" class="form-control" style=" width: 20%" id="hLane1"> </input>

One of the advantages of using the onblur instead of a onclik outside the input is that if the user is browsing through the key TAB that event will also be triggered.

3

As an add-on here goes the jQuery version:

$( "#hLane1" ).blur(_ => { alert( "Hoje é sexta ^.^ " ); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="form-control" style=" width: 20%" id="hLane1"> </input>

Documentation jQuery
.Blur()

1

You can use the . on function as multiple events and use click and Blur to do this:

$('.teste').on({
  click: function () {
    console.log('Fui clicado!')
  },
  blur: function() {
    console.log("Sai do input")
  } 
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="name" class="teste" placeholder="Escreva aqui...">

Browser other questions tagged

You are not signed in. Login or sign up in order to post.