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:
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:
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:
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.