How to properly call a function in an event handler

Hello guys, sorry to disturb you all; I'm getting an error on line 7 but I didn't understand why, can someone explain why please
const btn = document.querySelector('#__btn');
const text = document.querySelector('.content');
const source = 'scripts/callbacks.js';

btn.addEventListener('click', (loadScript) => {
text.textContent = 'Loading another JS Script . . .';
loadScript(source ,sayHello);

})


function loadScript (src, sayHello) {
const script = document.createElement('script');
script.src = src
script.onload = sayHello;
document.head.append(script);
console.log('should be executed first followed by callback');
}

function sayHello() {
console.log('Hello world !');
}
const btn = document.querySelector('#__btn');
const text = document.querySelector('.content');
const source = 'scripts/callbacks.js';

btn.addEventListener('click', (loadScript) => {
text.textContent = 'Loading another JS Script . . .';
loadScript(source ,sayHello);

})


function loadScript (src, sayHello) {
const script = document.createElement('script');
script.src = src
script.onload = sayHello;
document.head.append(script);
console.log('should be executed first followed by callback');
}

function sayHello() {
console.log('Hello world !');
}
No description
4 Replies
glutonium
glutonium2mo ago
the argument that is passed onto the call back function in the addEventListener() is an event object and not a function console log loadScript
btn.addEventListener('click', (loadScript) => {
text.textContent = 'Loading another JS Script . . .';
console.log(loadScript);
})
btn.addEventListener('click', (loadScript) => {
text.textContent = 'Loading another JS Script . . .';
console.log(loadScript);
})
and u will understand your mistake
Faker
FakerOP2mo ago
ahhhh I see the loadScript is an event object
glutonium
glutonium2mo ago
u might be more familiar doing
element.addEventListener("click", e => {
console.log(e);
})
element.addEventListener("click", e => {
console.log(e);
})
your localScript within the event listener in your code is the e here the convention is to call it e or event cause it is an event object
Faker
FakerOP2mo ago
yep I see, I totally messed up with the argument being passed
Want results from more Discord servers?
Add your server