The easiest way to solve this problem is to just add another character after the pound symbol like this:
<a href='#a' class="closeLink">close</a>
Problem solved. Yes, it was that easy. Some may hate this answer, but they cannot deny that it works.
Just make sure you don't actually have a section assigned to "a" or it will go to that part of the page. (I don't see this as often as I use to, though) "#" by itself, by default, goes to the top of the page.
JavaScript version:
myButton.onclick=function(e){
e.preventDefault();
// code
return false;
}
jQuery version:
$('.myButtonClass').click(function(e){
e.preventDefault();
// code
return false;
});
This just do the job well! :)
Although it seems to be very popular, href='#' is not a magic keyword for JavaScript, it's just a regular link to an empty anchor and as such it's pretty pointless. You basically have two options:
Implement an alternative for JavaScript-unaware user agents, use the href parameter to point to it and cancel the link with JavaScript. E.g.:
<a href="close.php" onclick="close(); return false">
When the noscript alternative is not available or relevant, you don't need a link at all:
<span onclick="close(); return false">Close</span>
Use href = "JavaScript:Void(0);"
return false is the answer, but I usually do this instead:
$('.closeLink').click( function(event) {
event.preventDefault();
...do the close action...
});
Stops the action from happening before you run your code.
If your code is getting passed the eventObject you could use preventDefault()
; returning false also helps.
mylink.onclick = function(e){
e.preventDefault();
// stuff
return false;
}