Skip to content
Advertisement

How can I make an element trigger a function on any, and all events?

I don’t think an explanation of my specific scenario would help much here. So in short I need to know how I can call a function on any and all events. The idea is to call the same function no matter what event happens to a specific element.

In my head the ideal way to do this would go something like:

<div onAnyEvent="function()"></div>

Rather than:

<div onClick="function()" onMouseover="function()" onKeypress="function()"></div>

Advertisement

Answer

The best method I have found through research is to create an event listener for each event on the same element like so:

window.onload = addListeners;

function addListeners(){
  if(window.addEventListener){
    document.getElementById('message').addEventListener('keydown',textarea_resize,false);
    document.getElementById('message').addEventListener('keyup',textarea_resize,false);
    document.getElementById('message').addEventListener('keypress',textarea_resize,false);
}

To explain a little further:

addEventListener('event to listen to', function_to_be_called, useCapture-value)

The first parameter is the event you want to listen to (ie. 'click' or 'keydown').

The second is the function that you want to call: (ie. validate_form).

-you can also send parameters into the function: validate_form(e, i).

The last value for use capture will usually be set to false for most uses, and false is the automatic value if you don’t specify any value. Further explanation can be obtained here!

So a full example might be: document.getElementById('message').addEventListener('keydown',textarea_resize,false); as I showed above.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement