Possible global function calls by tag?

In my source code, I have many examples similar to the following:

<input id="a" type="text" name="a" maxlength="40" onfocus="ThisOnFocus(this)" onkeydown="ThisOnKeyDown(this)" onkeyup="ThisOnKeyUp(this)" onblur="ThisOnBlur(this)"/> 

Each input tag ends with those onfocus, onkeydown, onkeyup, and onblur calls.

What I would like to do is to indicate globally that all input tags call these functions for these events. Is this something that can be done in JavaScript? Thanks!

Edit: I tried to place this in a script section, and none of my functions are called:

 document.onload = function() { var inputs = document.getElementsByTagName('input'); for (i = 0; i < inputs.length; i++) { inputs[i].onfocus = ThisOnFocus; inputs[i].onblur = ThisOnBlur; inputs[i].onkeyup = ThisOnKeyUp; inputs[i].onkeydown = ThisOnKeyDown; } } 

Edit: In addition, it is not necessary to distinguish between input flags and text fields, but all these functions apply only to text fields.

+4
source share
4 answers

You have a few questions:

  • onload is an event handler applicable to the window object.
  • Event processing functions wait for a parameter that you do not pass. In your markup, you, for example, ThisOnBlur(this) , but in the code you just use ThisOnBlur without passing an argument.

Here is how I would change your code:

 function createEventHandler(fn, input) { return function () { fn(input); }; } window.onload = function() { var inputs = document.getElementsByTagName('input'); for (i = 0; i < inputs.length; i++) { inputs[i].onfocus = createEventHandler( ThisOnFocus, inputs[i]); inputs[i].onblur = createEventHandler( ThisOnBlur, inputs[i]); inputs[i].onkeydown = createEventHandler( ThisOnKeyDown, inputs[i]); inputs[i].onkeyup = createEventHandler( ThisOnKeyUp, inputs[i]); } }; 

The createEventHandler function allows you to get a reference to a function that calls your existing event handlers with the correct arguments.

Here is an example: http://jsfiddle.net/YPNmd/

0
source

You can use grip and bubble. Note that a focus and blur event requires capture. In addition, you can use focusin and focusout events.

Live demo: http://jsfiddle.net/t2KdS/

+1
source

Have a look here: http://triaslama.wordpress.com/2008/07/22/four-ways-javascript-binding-event-listeners/

If I were you, I would choose jQuery. But it works in pure Javascript. :)

0
source

This is really a question of the word global scope . If your JS is scattered across several files, you will have to write the code of the above answers in a file that is called before the main file, which calls all the other JS functions.

If you have one file, put these lines at the top of each function. This makes it global in JS. But in this case, you can use the jQuery approach, since global variables are a fundamental point of failure. Refrain from using them as much as possible

0
source

Source: https://habr.com/ru/post/1383057/


All Articles