Adam Scot
Adam Scot

Reputation: 1409

How to run a function with no parameters on an event defined by event listener

I have a function which creates an input element and appends this to another element.

I am trying to make it, so that if an array is used as a parameter of this function, then data from the array is used as the value of the input element. If no array is specified as a parameter, then the input value should be empty.

Here is my code

HTML

<div id="app></div>

Javascript

let app = document.getElementById('app')
let people = [["Adam",10],["Peter",90],["John",30],["Stephen",50]]

for (var key in people) {
  showName(people[key])
}


function showName(pData) {
  let singleName = document.createElement('input')
  
          if (typeof pData !== 'undefined') {
            singleName.value = pData[0]
        }
  
      app.append(singleName)
}


let button = document.createElement('button')
    button.addEventListener('click',showName)
    button.innerHTML = "Add name"
    app.prepend(button)
   

This works fine, I can run the function with a parameter and without a parameter and it works as expected.

When however, I set the function to trigger via an event listener and without a parameter, I can an input with a value of 'undefined', this is not the case if I run the function by writing showName().

This therefore leads me to believe that some kind of parameter is being passed when the event is triggered via an event listener. Is this the case? And if so, how do I make it so that the button creates an input element with no value?

Upvotes: 0

Views: 442

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 84922

This therefore leads me to believe that some kind of parameter is being passed when the event is triggered via an event listener. Is this the case?

Yes, your function will get passed the event object, which contains information about the click that took place

And if so, how do I make it so that the button creates an input element with no value?

Instead of passing showName directly into addEventListener, create a new function. That function will ignore the event object, and call showName with no parameters:

button.addEventListener('click', (event) => showName())
// Or:
button.addEventListener('click', () => showName())

Upvotes: 4

Related Questions