How to Add a Locksmith to the keypress event on all pure javascript inputs?

Asked

Viewed 655 times

1

I need to have a listener for the event keypress of all the inputs of my application, I wanted to know the most correct and performative way to do this, it would be a behavior similar to $('input').on('keypress') jQuery but wanted to do it in pure javascript.

I tried some alternatives like those of this link: Add event to multiple elements without being inside a for loop but it’s not happening.

  • Would Jquery be an "impure" Javascript? srsrs

  • @Danielomine rsrs! Using pure javascript is faster than using frameworks, but it’s in my opinion risky due to cross browser.

  • Exactly. It is that in the end you will end up arriving in the same as in Jquery. You can go straight into Jquery code and extract only the parts that matter. rsr.

  • @Danielomine, kkkkkk... Heresy use jQuery, is that I am studying javascript and the focus here is performance, but really would have to have additional treatments to not have crossbrowser problems...

2 answers

2


Follow the solution with comments.

Add the code at the end of your HTML page. It’s good practice to add the code or link to the .js at the bottom of the page when this does not need to be executed before the content is rendered.

Read on here, will help you understand what I wrote above.

//É importante que o seu código seja executada somente após a renderização de todos os inputs.
//Caso contrário, o script irá fazer referência a um elemento que
//não foi renderizado, por tanto não existe no momento.

//A técnica abaixo chama-se "self executing", ou seja
//automaticamente será executado o código.
(function() {
    //Array com todos os elementos input.
    //Cada indice do array "inputs" representa contém um objecto input
    inputs = document.getElementsByTagName('input');

    //É atribuído o evento "keypress" a cada objecto input
    //Definimos também qual função será executa, no exemplo dei o nome de "minhaFuncao"
    for (index = 0; index < inputs.length; ++index)
        inputs[index].addEventListener("keypress", minhaFuncao);
})();

function minhaFuncao(event) {
  console.log(event.target.id); 
}
  • @Felipemoraes, is sure that the DOM object will be available? Jsfiddle

  • @Tobymosque yes, when the code or link to js is inserted at the end, and it is a good practice when the code is not needed until the page is rendered. I’ll add the information.

  • @Felipemoraes, thanks man, worked this way, I did not comment because I thought q would be simple, but I need to send the input object that was pressed or its id, but when you passed some parameter Listener only works when opening the page, after Listener no longer works, you know how I can pass parameter in this case?

  • @Felipemoraes, I think I got, instead of passing parameter, I left the IIFE the way it is and in the "myFuncao" I used e.target, it seems that it worked, this is correct?

  • @Joãopaulo updated the answer with his doubt. It is passed to the function "myFuncao" the parameter "Event", which happened to give the same name.

  • @Felipemoraes, blz cara gave it right, a hug. PS.: I’m new here, do you have something on the platform like: assign better response in my opinion, increase user points or something? Or end as resolved doubt..

  • @Felipemoraes, the technique self executing does not guarantee that the script will be executed after rendering the DOM objects, until pq this technique attempts to solve another problem, create a closure to limit the scope of the script. As for putting the script at the end of the body to be a good practice, this is contestable, you can and should use the defer and the async to define when and how scripts will be loaded. Deep Dive into the murky Waters of script loading

  • @Joãopaulo yes, there are buttons on the left side of each answer, where you can choose the one that solves your problem (it’s good for others with the same problem to see the chosen solution), can give negative or hint for a response... take a look here at the help center to understand how the community works: http://answall.com/help

  • @Tobymosque I know what this is about, I know there is Defer/async, but that is not the point of the question or the solution, we can not discuss it here.

Show 4 more comments

0

You could do it this way:

/**
 *
 * @param el Object element a ser adicionado o evento
 * @param func Function função a ser adicionada
 */
function addKeypress(el, func) {

  if (el.addEventListener) {
    el.addEventListener('keypress', func, false); 
  } else if (el.attachEvent)  {//Internet Explorer antigos
    el.attachEvent('onkeypress', func);
  }

}

function yourFunc() {
	alert('Teste');
}

(function(d) {

  var inputs = d.getElementsByTagName('input');
  
  for (var input in inputs) {
  	addKeypress(inputs[input], yourFunc);
  }

})(document);
input {
  diplay: block;
  width: 100%;
}
<label for="txt_input1">Input 1:<input type="text" id="txt_input1" nome="txt_input1"></label>
<label for="txt_input2">Input 2:<input type="text" id="txt_input2" nome="txt_input2"></label>
<label for="txt_input3">Input 3:<input type="text" id="txt_input3" nome="txt_input3"></label>
<label for="txt_input4">Input 4:<input type="text" id="txt_input4" nome="txt_input4"></label>

  • 1

    Dude, vi q has a fallback for IE <= 8 neh, thanks

Browser other questions tagged

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