I have a javascript that executes within a element like : <a href="javascript:doSomething();"> but it doesn't execute on window.load , anyone knows why does that happen ?
-
because you didnt execute the javascript on window.load and used it on a.click instead maybe.Numenor– Numenor2009-12-29 14:22:35 +00:00Commented Dec 29, 2009 at 14:22
-
did you mean window.onload instead of window.load?Eran Medan– Eran Medan2009-12-29 14:26:09 +00:00Commented Dec 29, 2009 at 14:26
4 Answers
With the example above doSomething() will only be called when the user clicks on the anchor. If you want it to execute on window.load you need to put the code in the head. i.e.
<script type="text/javascript">
window.onload = doSomething;
</script>
Also, if you're going to be using the onload event a lot I would personally recommend getting jQuery and using it's 'on DOM ready' event. This way your javascript will appear seamless to the end-user and won't have a flickering effect.
Comments
Assuming you did all the other suggestions, there is always a chance that someone later in the code (after your either <body onload=... or window.onload = ...) did exactly the same, and has overriden you.
If it happens to be the case (low chance) the solution to support both of your onload hooks, is window.attachEvent("onload", doSomething)
1 Comment
attachEvent way of adding events handlers. the benefits are numerous and well documented.If I understand your problem correctly, you want to set an attribute in an element, calculating it dynamically via javascript, so that when the page is loaded your link points to the return value of "doSomething()".
For that you can use javascript's DOM manipulation utility functions. In your case something like:
<a id="myLink">my anchor</a>
...
<script type="text/javascript">
getElementById('myLink').href = doSomething();
</script>