I am building a demo movie app so I decided to assign onclick events with a function that gets me some movie related data.
The problem arises when I click on the target links I want to work on, giving me back an undefined function.
Here’s the code:
function getMovieList(key,value) { console.log(key,value)}
function getLanguages() {
const languagesList = document.querySelector("[languages]");
const languagesArray = [
["en-US", "english"],
["it", "italian"],
["de", "german"],
["hi", "indian"],
];
const languagesMap = new Map();
languagesArray.forEach( languages => {
const [idLanguage,language] = languages;
languagesMap.set(idLanguage,language);
languagesList.innerHTML += `
<li class="capitalize" onclick="getMovieList(with_original_langauge=${idLanguage}, ${language})">
<a href="index.html" language-id=${idLanguage}">${language}</a>
</li>
`;
} );
}
getLanguages()
When I inspect my links they do have the given arguments but if I click on them, then it says my function is undefined so I cannot get the values back.
Why is that ?
I tried the method window.onload expecting to load the function beforehand and get it as defined,but still it did not work.
2
Answers
The
getMovieList()
function is called asynchronously, which means that the default behaviour of the<a>
link is called before the function is executed.Use
event.preventDefault();
in the event handler, and change thehref
manually from the function body.EDIT : My answer have changed since your edit!
There’s something that looks at your code but you have to add a real
location.href
in the function.Here it makes just an alert with some URL parameters for the demo.