0
  let toggleForm = function() {
    // code here
  }

  document.getElementById('one').addEventListener("click", toggleForm, false);

  document.getElementById('two').addEventListener("click", toggleForm, false);

In toggleForm I'd like to know whether element one or two fired the event. How would you go about doing that?

1 Answer 1

2

Use e.target:

<button id = 'one'>One</button>
<button id = 'two'>Two</button>
<script>
  var one = document.getElementById('one'),
    two = document.getElementById('two');
  let toggleForm = function(e) {
    if (e.target === one) alert('One');
    else alert('Two');
  };
  one.addEventListener("click", toggleForm, false);
  two.addEventListener("click", toggleForm, false);
</script>
Sign up to request clarification or add additional context in comments.

3 Comments

Awesome! I assume what's going on behind the screens is that inside addEventListener, an object (in our case 'e') get's passed into the callback?
Yes, e is the event object that gets passed to the listener. It has lots of other properties as well.
Very cool! Just did a console.log on the object and noticed the other properties. Thanks again

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.