2

How to add multiple event listeners in the same initialization?

For example:

<input type="text" id="text">
<button id="button_click">Search</button>

JavaScript:

var myElement = document.getElementById('button_click');
myElement.addEventListener('click', myFunc());

This is working correctly however I would like to have another event listener for this input filed in the same call if that is possible, so when user clicks enter or presses the button it triggers the same event listener.

Just one note. User needs to be focused on the input field to trigger an "enter" event.

1
  • the signature for addEventListener is ('click', myFunc) Commented Jun 13, 2013 at 8:55

4 Answers 4

2

Just bind your function to 2 listeners, each one of the wished element:

document.getElementById('button_click').addEventListener('click', myFunc);
document.getElementById('text').addEventListener('keyup', keyupFunc);

where the new function test if the user pressed enter and then execute the other function :

function keyupFunc(evt) {
    if(evt.keyCode === 13) // keycode for return
        myFunc();
}

Working jsFiddle : http://jsfiddle.net/cG7HW/

Sign up to request clarification or add additional context in comments.

3 Comments

This keyCode is not being triggered...when I put alert() inside keyupFunc at the top alert is triggered...so basically it is going inside the function but not passing this if statement..any idea?
got it! problem was in === and when I did == everything was ok
@user123_456 : yes sorry, I initially thought keyCode was a string, but it was a number so evt.keyCode === 13should work. But you can use == it removes the check over the type...
2

I think the best way to do this is by using for loops.

const events = ["click", "mouseover"]
for (i in events) {
   document.getElementById("button_click").addEventListener(events[i], () => myFunc())
}

The code above loops through every events inside an array and adds it to the button.

Comments

0

Try this:

 function addMultipleEvents(elements, events){
      var tokens = events.split(" ");
      if(tokens.length == elements.length){
          for(var i = 0; i< tokens.length; i++){
              elements[i].addEventListener(tokens[i], (e.which == 13 || e.which == 48)?myFunc:); //not myFunc()
          }
      }
 }

 var textObj = document.getElementById("textId");
 var btnObj = document.getElementById("btnId");
 addMultipleEvents([textObj,btnObj], 'click keyup');

UPDATE:

  function addMultipleEvents(elements, events) {
      var tokens = events.split(" ");
      if (tokens.length == elements.length) {
          for (var i = 0; i < tokens.length; i++) {
              elements[i].addEventListener(tokens[i], myFunc); //not myFunc()
          }
      }
  }

  var textObj = document.getElementById("textId");
  var btnObj = document.getElementById("btnId");
  addMultipleEvents([btnObj, textObj], 'click keyup');

  function myFunc(e) {
      if (e.which == 13 || e.which == 1) {
          alert("hello");
      }
  }

Working Fiddle

4 Comments

I am not sure to correctly understand the question, but I guess that the OP means that the enter event should be fired on the input element as though the click event will be fired by the button element...
@SamuelCaillerie I need exactly what you said
Adding a keyup event to a button and seems a bit strange, isn't it? I think that decoupling of the 2 handlers (but with calling a single function) is better...
@SamuelCaillerie I am not adding keyup event to button. I am adding events parallelly to the array of objects. The OP was looking to call the same function. So, I did this. :). I mean keeping the if condition inside the myFunc instead of keeping it out. overall, it looks strange but does work. ")
0

Yeah this is a good question and can apply to other scenarios. You have a form and a user will have input text field, a radio box, a select option. So now you want the submit button to go from disabled to enabled. You decide to add an event listener to check if fieldA and fieldB and fieldC is first to enable submit button.

If you use event listener on Keyup", and all your fields are valid, the submit button will become enabled only if the last field is a text field because the event will only be triggered when you let go the key. This means it will not trigger if the radio box or select option is selected with your mouse. We must not rely in the order the fields are filled for the logic to work. Again, If you use "click", it sucks, because user will have to click somewhere on page in order for the event listener to fire and run the logic. So i think we'll need an event lister on mouseup, keyup and change for this example below. I assume you made all your validations and variables for the form fields already. We need a function with parameters of multiple events names as a string, the element we want to target (document, or button or form), and a custom function that contains our logic.

// Create function that takes parameters of multiple event listeners, an element to target, and a function to execute logic

function enableTheSubmitButton(element, eventNamesString, customFunction) {
  eventNamesString.split(' ').forEach(e => element.addEventListener(e, listener, false));
}

// Call the above function and loop through the three event names inside the string, then invoke each event name to your customFunction, you can add more events or change the event names maybe mousedown, keyup etc.
enableSubmitButton(document, 'keyup mouseup change', function(){

  // The logic inside your customFunction
  if (isNameValid && isLocationValid && isProjectValid){
    publishButton.disabled = false;
  } else {
    publishButton.disabled = true;
    // Do more stuff like: "Hey your fields are not valid."
  }

});


// The isNameValid isLocationValid, isProjectValid are coming from your previous validation Javascript for perhaps a select field, radio buttons, and text fields. I am adding it as an example, they have to be equal to true. 

// The publishButton is a variable to target the form submit button of which you want enabled or disabled based one weather the form fields are valid or not. 
// For example: const publishButton = document.getElementById("publish");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.