I am learning the basics and trying to play around with JS. My question is how can I use a function written outside addEventListener. Right now I am using the following code:
ageCalculatorButton.addEventListener('click',function (event){
var birthYear= prompt("What year you were born");
})
Now let's suppose I am trying to reuse a piece of code, how will I call the function from addEventListener. I am trying to accomplish the following:
ageCalculatorButton.addEventListener('click',ageInDays())
function ageInDays(){
var birthYear= prompt("What year you were born");
}
Is it even possible or am I just hungup in solving an insolvable problem.
Firstly, you can reuse functions from outside.
try it like this:
ageCalculatorButton.addEventListener('click',ageInDays)
function ageInDays(){
var birthYear= prompt("What year you were born");
}
Or even you can pass in the prompt function like this:
ageCalculatorButton.addEventListener('click',ageInDays(prompt))
function ageInDays(func){
return function(){
var birthYear=func("What year you were born");
}
}