Juri Strumpflohner
Juri Strumpflohner Juri is a full stack developer and tech lead with a special passion for the web and frontend development. He creates online videos for Egghead.io, writes articles on his blog and for tech magazines, speaks at conferences and holds training workshops. Juri is also a recognized Google Developer Expert in Web Technologies

Problem: launching javascript from hyperlinks without redirecting

2 min read

When I'm launching javascripts on a webpage I often use hyperlinks instead of buttons (it depends however on the context). So you may write something like the following
<a id="myLaunchLink" href="#" onclick="myJavaScriptFunction();">click me</a>
In such a case everything would be fine unless you reuse that piece, i.e. it is placed inside a user control which may appear multiple times on a page. In that case you'll get a problem with the id of the link since you have the situation where more links with the same id "myLaunchLink" reside on the same page.
So instead of using a plain link you may use an asp.net Hyperlink (<asp:Hyperlink..>) element. But I mean that's the abvious step. What happened to me however was that having href="#", it caused the page to redirect to the user-controls path: assume my page url is something like "http://www.mydomain.com/mypage.aspx", it redirected the page to the url "http://www.mydomain.com/myusercontrols/someotherfolder/#". Removing the href tag (or the NavigateURL property of the Hyperlink control) has the side-effect that the CSS classes referenced by something like
a {     ...  }
don't apply. So the href element has to stay.
Actually the solution is quite simple. In a browser you can for instance launch a javascript function or statement directly from the browser's address bar by typing "javascript:alert('hello there')". The same applies also to the href tag. So the final result looks as follows:
<asp:hyperlink href="javascript:;" id="myLaunchLink" runat="server" onclick="myJavaScriptFunction();">Suche</asp:hyperlink>
One may now argue why not to launch the "myJavaScriptFunction" call directly in the href part instead of just doing nothing there. Well that's true in this simple case but it may change when you attach the javascript event-handler dynamically from within another javascript function or ajax extender.
Questions? Thoughts? Hit me up on Twitter
comments powered by Disqus