0

Something weird happens that I can't explain! When i call a function from the javascript for example:

<script type='text/javascript'>
  callFunction()
</script>

The function is called but it produces an error for non declared variable.

When i call the same function through a link i.e. :

<a  href="#" onclick="callFunction(); return false;"> Link  </a>

The function runs succesfully and produces the correct output!

Any ideas why this happens?

2 Answers 2

1

most likely you try to call the function before it became declared - make sure that this isn't the case and that the function isn't declared somewhere below the block where you try to call it.

Sign up to request clarification or add additional context in comments.

Comments

1

By the time, the first script is executed, there is no function callFunction yet. When you click the link however, the page has already loaded far enough so that the function is available.

The solution is to wait for the page to load, before you call functions. Nearly all JavaScript frameworks (JQuery, MooTools etc.) offer an event handler, that is called when the DOM, that is the underlying structure of the document, is ready. If you don't want to use a framework, you can also wait for the document to load (i.e. the load event), but that is usually called later than domready.

1 Comment

Thanks that was the solution!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.