Home > OS >  Function is not accessible after onload event. "TypeError: {someFunctionName} is not a function
Function is not accessible after onload event. "TypeError: {someFunctionName} is not a function

Time:04-20

I have written a small and simple slider with Javascript. Because I want to be sure that the slider works when I load the javascript in the footer of the page. I added an onload event and copied the whole slider application inside the event. In the HTML I unfortunately have an inline onclick element in a tag. But since I have the code inside the onl oad scope the onclick doesn't work anymore. My idea is not to bind the event inline in the html but directly in the javascript. That should work. But I am also interested if it is possible to do it with the inline onclick.

Question What do I have to do so that the onclick element addresses the corresponding function within the onclick function?

document.querySelector('body').onload = function() { 
  
  function init() {
    // ...
  }
  
  const f2 = function() {
    // ...
  }
  
  init();

  /* that will work */
  const anchorPrev = document.querySelector('.prev');
      anchorPrev.addEventListener('click', () => {
      console.log('prev');
  });
  
  /* My question */
  function next() {
    console.log('next')
  }
};
a {
  cursor: pointer;
}
<body>
    <a  onclick="next()">next (I'm curious to know if it works!?)</a><br/>
    <a >prev (Will work)</a>
</body>

CodePudding user response:

Two issues:

  1. It's better to wait for the DOMContentLoaded event on the window object.
  2. You're defining the function within the scope of the function, so it's not globally accessible. This means that the onclick can't see the function. Use a let variable, then set the function inside the listener callback like this:

<button onclick="log()">click me</button>

<script>
    let log;

    window.addEventListener('DOMContentLoaded', () => {
        console.log('loaded');
        log = () => console.log('clicked');
    });
</script>

CodePudding user response:

You can add that the onl oad event = function next()

JavaSript code:

document.querySelector('body').onload = function() { 

  const a = document.querySelector('a')
  a.onclick = function next() {
    event.preventDefault()
    console.log('next')
  }
};
  • Related