Callback running when loading the page

Asked

Viewed 124 times

8

I’m taking some tests to learn more about callback in javascript and found the following difficulty:

function nome_existe(element) {
  console.log(element.id);
}
window.onload = function() {
  Array.from(document.getElementById("form_id")).forEach(function(element, index) {
    element.addEventListener("blur", nome_existe(element));
  });
};
<form id="form_id" method="POST" action="/cloud/criar-conta.php" autocomplete="off">
  <input type="text" name="input_nome" id="input_nome" placeholder="Insira um nome" value="" /><br/>
  <input type="text" name="input_email" id="input_email" placeholder="" value="Insira um email" /><br/>
  <input type="text" name="input_email_c" id="input_email_c" placeholder="" value="Confirme seu email" /><br/>
  <input type="text" name="input_tel" id="input_tel" placeholder="" value="(DDD) - _____ - ____" /><br/>
  <input type="password" name="input_senha" id="input_senha" placeholder="Digite uma senha" value="" /><br/>
  <input type="password" name="input_senha_c" id="input_senha_c" placeholder="Confirme sua senha" value="" /><br/>
  <input type="checkbox" name="input_check" id="input_check" onblur="valida_check()" />
  <p id="termo_cad">Concordo com os Termos de Serviçes e Política de Privacidade</p>
  <input type="submit" name="sub_btn" id="sub_btn" value="Enviar" />
</form>

The section places the elements of a form in a array and theoretically (in my mind) should assign a listnerto the camp that received the event blur and then log in the id of the element in the console.

The difficulty is: Why running the event onload, is logged into the console ids of all elements, even without the event occurring blur?

  • Show what’s going on, I imagine it’s normal, after all it’s adding all of them, the call is something else.

  • This occurs in all browsers?

  • What is happening is: console.log(element.id);. I have a form with 8 elements of the type text. Then row after row in the console is shown the field id. However I would like this to occur only in the field where there is the blur.

  • @Renan yes for Chrome and FF.

  • It is well at the discretion of the same developer @Magichat, the way it was was not wrong. I only edited because the visually line where has the Array was along with the keys that opens the function and was somewhat confused the analysis. I only used the automatic (Organize) snippet :p identator

  • A blz... To tell you the truth I don’t know how six can, indent each language in a style, I’ve given up everything the same... May Even so.. Vlw man...

Show 1 more comment

3 answers

5


If the function is not anonymous it will be invoked in the event record. In your case, you can invoke nome_existe within an anonymous function on callback of blur:

function nome_existe(element) {
  console.log(element.id);
}
window.onload = function() {
  Array.from(document.getElementById("form_id")).forEach(function(element, index) {
    element.addEventListener("blur", function() {
      nome_existe(element);
    });
  });
}
<form id="form_id" method="POST" action="/cloud/criar-conta.php" autocomplete="off">
  <input type="text" name="input_nome" id="input_nome" placeholder="Insira um nome" value="" /><br/>
  <input type="text" name="input_email" id="input_email" placeholder="" value="Insira um email" /><br/>
  <input type="text" name="input_email_c" id="input_email_c" placeholder="" value="Confirme seu email" /><br/>
  <input type="text" name="input_tel" id="input_tel" placeholder="" value="(DDD) - _____ - ____" /><br/>
  <input type="password" name="input_senha" id="input_senha" placeholder="Digite uma senha" value="" /><br/>
  <input type="password" name="input_senha_c" id="input_senha_c" placeholder="Confirme sua senha" value="" /><br/>
  <input type="checkbox" name="input_check" id="input_check" onblur="valida_check()" />
  <p id="termo_cad">Concordo com os Termos de Serviçes e Política de Privacidade</p>
  <input type="submit" name="sub_btn" id="sub_btn" value="Enviar" />
</form>

Calling a declared function outside the callback:

A very common implementation is to invoke a function outside without arguments where the function will have the scope of who invoked:

function nome_existe() {
  console.log(this.id);
}
window.onload = function() {
  Array.from(document.getElementById("form_id")).forEach(function(element, index) {
    element.addEventListener("blur", nome_existe);
  });
}
<form id="form_id" method="POST" action="/cloud/criar-conta.php" autocomplete="off">
  <input type="text" name="input_nome" id="input_nome" placeholder="Insira um nome" value="" /><br/>
  <input type="text" name="input_email" id="input_email" placeholder="" value="Insira um email" /><br/>
  <input type="text" name="input_email_c" id="input_email_c" placeholder="" value="Confirme seu email" /><br/>
  <input type="text" name="input_tel" id="input_tel" placeholder="" value="(DDD) - _____ - ____" /><br/>
  <input type="password" name="input_senha" id="input_senha" placeholder="Digite uma senha" value="" /><br/>
  <input type="password" name="input_senha_c" id="input_senha_c" placeholder="Confirme sua senha" value="" /><br/>
  <input type="checkbox" name="input_check" id="input_check" onblur="valida_check()" />
  <p id="termo_cad">Concordo com os Termos de Serviçes e Política de Privacidade</p>
  <input type="submit" name="sub_btn" id="sub_btn" value="Enviar" />
</form>

Calling a function declared outside of callback with arguments

If necessary to use arguments in the declared function, one way would be to bind:

function nome_existe(arg) {
  console.log(this.id, arg);
}
window.onload = function() {
  Array.from(document.getElementById("form_id")).forEach(function(element, index) {
    element.addEventListener("blur", nome_existe.bind(element, 'Index: ' + index));
  });
}
<form id="form_id" method="POST" action="/cloud/criar-conta.php" autocomplete="off">
  <input type="text" name="input_nome" id="input_nome" placeholder="Insira um nome" value="" /><br/>
  <input type="text" name="input_email" id="input_email" placeholder="" value="Insira um email" /><br/>
  <input type="text" name="input_email_c" id="input_email_c" placeholder="" value="Confirme seu email" /><br/>
  <input type="text" name="input_tel" id="input_tel" placeholder="" value="(DDD) - _____ - ____" /><br/>
  <input type="password" name="input_senha" id="input_senha" placeholder="Digite uma senha" value="" /><br/>
  <input type="password" name="input_senha_c" id="input_senha_c" placeholder="Confirme sua senha" value="" /><br/>
  <input type="checkbox" name="input_check" id="input_check" onblur="valida_check()" />
  <p id="termo_cad">Concordo com os Termos de Serviçes e Política de Privacidade</p>
  <input type="submit" name="sub_btn" id="sub_btn" value="Enviar" />
</form>

  • Massa, tell me one thing I need anonymity, it has as I pass only the function?

  • Not necessarily @Magichat. You can name the function as long as it has not been declared outside the callback. If you want the function to be uncoupled, you should call it without invocation by passing the context. I updated the answer =]

  • 1

    Show...nice, vlw man

  • If there are no parameters you can just put the function name without the parentheses and it will not execute at the time of the declaration. But if it has parameters there I believe that really does not have as without using the anonymous, unless it is possible using those stops of .call but I can’t tell you if there’s a way.

  • Yes @Pauloroberto, com bind.

4

If you want to save a reference to the element being iterated you can use .bind() that will create a function, passing as first argument the element.

But you really don’t need to pass up your job nome_existe and use the this within it. The this is always the element that has the .addEventListener.

Example:

function nome_existe(event) {
  console.log(this.id, event.type);
}
window.onload = function() {
  Array.from(document.getElementById("form_id")).forEach(function(element, index) {
    element.addEventListener("blur", nome_existe);
  });
};

function valida_check(){

}
<form id="form_id" method="POST" action="/cloud/criar-conta.php" autocomplete="off">
  <input type="text" name="input_nome" id="input_nome" placeholder="Insira um nome" value="" /><br/>
  <input type="text" name="input_email" id="input_email" placeholder="" value="Insira um email" /><br/>
  <input type="text" name="input_email_c" id="input_email_c" placeholder="" value="Confirme seu email" /><br/>
  <input type="text" name="input_tel" id="input_tel" placeholder="" value="(DDD) - _____ - ____" /><br/>
  <input type="password" name="input_senha" id="input_senha" placeholder="Digite uma senha" value="" /><br/>
  <input type="password" name="input_senha_c" id="input_senha_c" placeholder="Confirme sua senha" value="" /><br/>
  <input type="checkbox" name="input_check" id="input_check" onblur="valida_check()" />
  <p id="termo_cad">Concordo com os Termos de Serviçes e Política de Privacidade</p>
  <input type="submit" name="sub_btn" id="sub_btn" value="Enviar" />
</form>

1

The functions callbacks that handle events in Javascript are set to the object describing the event as a parameter. The event object has the attribute target representing the target element of this event. In this case, the function parameter nome_existe will be the event blur and the attribute target of this object will be the form field. This way, you can access the id field with evento.target.id. See the example below:

function nome_existe(evento) {
  console.log(evento.target.id);
}

window.onload = function () {

  for (let element of document.getElementById("form_id")) {
    element.addEventListener("blur", nome_existe);
  }
  
}
<form id="form_id" method="POST" action="/cloud/criar-conta.php" autocomplete="off">
  <input type="text" name="input_nome" id="input_nome" placeholder="Insira um nome" value="" /><br/>
  <input type="text" name="input_email" id="input_email" placeholder="" value="Insira um email" /><br/>
  <input type="text" name="input_email_c" id="input_email_c" placeholder="" value="Confirme seu email" /><br/>
  <input type="text" name="input_tel" id="input_tel" placeholder="" value="(DDD) - _____ - ____" /><br/>
  <input type="password" name="input_senha" id="input_senha" placeholder="Digite uma senha" value="" /><br/>
  <input type="password" name="input_senha_c" id="input_senha_c" placeholder="Confirme sua senha" value="" /><br/>
  <input type="checkbox" name="input_check" id="input_check" onblur="valida_check()" />
  <p id="termo_cad">Concordo com os Termos de Serviçes e Política de Privacidade</p>
  <input type="submit" name="sub_btn" id="sub_btn" value="Enviar" />
</form>

From Ecmascript 2015 it is possible to use the notation for ... of as I used above. The logic about callback, which is the context of the question, it is exactly the same. It can be applied together with the Array.forEach in the same way. I used it as a way to complete the other answers by presenting a different form.

  • 1

    Em construção... publiquei sem querer ;p kkkkkkk first time I see this, creative

Browser other questions tagged

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