user1904218 user1904218 - 3 months ago 8
Javascript Question

Accessing data from callback function

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?

Answer

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>
Comments