I seem to make this mistake  repeatedly: I have a hyperlink on a page and rather than execute another URL I want it to execute a small bit of JavaScript code. Something like click a button and hide another control on the page:


<a href="javascript:document.getElementById('DragPanel').style.display='none';">Click</a>


This might seem reasonable, but if you run this code you’ll quickly find out that this doesn’t work. Well, the control hides alright – but so does everything else <s>. The entire page in fact navigates and it returns a new DOM with none as the value. Slightly unexpected eh? Not quite sure how the browser detects this value, but in any case it navigates the page somewhere I don't want it to navigate to.


There are a few ways around this. First you can navigate with a function call:


<a href="javascript:DoSomething();">Click</a>


function DoSomething()






This works and appropriately runs the code in the function without navigating the page. However, you have to be careful not to return any values from the function or else you get the same behavior I showed above where the result value becomes the new document displayed.


Since calling a function is OK, you can do something like the following too:


<a href="javascript:{document.getElementById('DragPanel').style.display='none';}">Click</a>


Which essentially defines an inline function and lets you execute the desired code. One downside to this is that the execution context changes so the the this pointer doesn’t point at the control any longer, but at the Window. It’s basically an anonymous function that’s being called on the fly and so it becomes a browser global functon tied to Window.


If you do need the this pointer you can use another approach:


<a href="javascript:{}" onclick="document.getElementById('DragPanel').style.display='none';alert(this.id);" id="MyLink">Click</a>


You might wonder why the null function {} link? You need something valid in the HREF attribute in order for the Anchor to show as a link, but yet something that doesn't actually navigate the page. Leaving the HREF=”” blank doesn’t do it because that basically means to re-load the current page. The null function does nothing, yet is a valid value  which is exactly what's needed here. javascript:; also works.


By using onclick() you’re bypassing the navigation operation of the link so you can just use plain in context code to what you need.  As you can see in the snippet you can also access the this point in this way.


It’s actually easier to just use a plain label with onclick, but often times you do want the link behavior - the proper  mouse pointer, link highlighting etc. - and so it’s still frequently reqiured to use HREF links (or ASP.NET LinkButtons) for link display. If you are using an ASP.NET LinkButton you can set the NavigateUrl with the javascript:{} link. Otherwise operationis identical.