You see both of these methods being used so often that you have to wonder – which is correct?
href=”javascript:f()”
vs
href=”#” onclick=”javascript:f()”
The classic ill side-effect that can occur when using the javascript: within a href attribute is when the function returns a value. Eg when opening a new window using window.open() – it returns an object reference to the new windows. In some browsers this will redirect to an otherwise blank page except for the word “[object]” (IE) or “[object Window]” (Netscape 4.x). However, assigning the window.open method to a variable avoids this. So:
href=”javascript:window.open();” will redirect the opener to [object] or [object Window]
href=”javascript:var newWin = window.open();” will pop the window without an opener redirect
Another trick is to wrap the function call in void as follows. href=”javascript:void(window.open());”
However, I believe that best practice is placing the target URI in the href attribute (like a normal link) or some descriptive text and placing the javascript in an onclick event handler (with the addition of “return false” at the end to cancel the link’s default behavior).
When you use “return false” on onclick eg. onclick=”functionName();return false” the browser doesn’t try to go to whatever is specified in the href when the link is clicked. If the onclick calls a submit function then you have effectively asked the browser to go to the href and the action of whatever form you are submitting.
So this is probably the best of both worlds.
href=”javascript://Open A New Window” onclick=”window.open();return false;”
Other possibilities for the href are
thanks a lot for this info !!
Very useful indeed. Thanks!
Great Info. Saved me a lot of time.
Thanks a lot.
Thanks, this was exactly what I needed. Very helpful
Cheers!