0

Basically I use the addEventListener function to bind events to an element. But you often see that events are created inline. So onclick="fnName(this)" and onkeyup="fnName()" etc.

Questions: Using the example <input onkeyup="fnName(this)" />.

  1. is a new event now created for each letter or does the tag parameter onkeyup initialise the event once?
  2. Which variant needs less computing time? I assume that addEventListener is more perfomanant, isn't it?
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79

1 Answers1

1
  1. New event created on every keyup, you can filter for specific keys in you function using if conditions event.key == "SOME_KEY"

  2. It's Micro-optimization with negligible difference, not much worth. A difference worth mentioning, you can multiple functions on same event using addEventListener while it wouldn't work in inline events.

<button id="btn1">Button 1</button>
<button id="btn2">Button 2</button>

<script>
  function function1() {
    console.log("Function1")
  }

  function function2() {
    console.log("Function2")
  }

  function function3() {
    console.log("Function3")
  }

  function function4() {
    console.log("Function4")
  }

  var btn1 = document.getElementById("btn1")
  var btn2 = document.getElementById("btn2")

  btn1.onclick = function1
  btn1.onclick = function2

  btn2.addEventListener("click", function3, false)
  btn2.addEventListener("click", function4, false)
</script>

Output in console:

Function2
Function3
Function4

Note: Both approaches will create a new event on every keyup, thus not making any difference. The comparison can be drawn only for single/equal number of event(s).

References:

  1. dillionmegida.com/p/inline-events-vs-add-event-listeners
  2. addEventListener vs onclick
Aahan Agarwal
  • 391
  • 2
  • 6
  • But you can attach multiple inline Events to the tag. So you can watch for multiple events, too. – Maik Lowrey Feb 11 '23 at 12:10
  • 1
    @MaikLowrey my bad, I phrased the sentence incorrectly thus changing it's meaning. I've corrected it now in the answer itself! – Aahan Agarwal Feb 11 '23 at 12:22
  • No problem :-) But thx for correcting. see u – Maik Lowrey Feb 11 '23 at 12:37
  • Sorry, I have to comment again. I don't think it's a good idea to copy things from other pages and paste them here 1:1 without mentioning the source. https://dillionmegida.com/p/inline-events-vs-add-event-listeners/ – Maik Lowrey Feb 11 '23 at 12:43
  • 1
    Sorry, I am new here. Thought I did mention the use of online sources, I've now listed them as well. – Aahan Agarwal Feb 11 '23 at 12:51