jQuery hyperlinks - href value?
On my website I use jQuery to hook the events of elements, namely hyperlinks. As these hyperlinks only perform actions on the current page, and do not lead anywhere, I have been putting a href attribute of "#" in:
<a href="#">My Link</a>
However in some browsers this causes the page to scroll right to top which is obviously undesirable behaviour. I've tried using a blank href value, or not including one, but then the mouse does not change to the hand cursor upon hovering.
What should I put in there?
Solution 1:
$('a').click(function (event)
{
event.preventDefault();
//here you can also do all sort of things
});
Then you can put in every href
whatever you want and jQuery will trigger the preventDefault()
method and you will not be redirected to that place.
Solution 2:
Those "anchors" that exist solely to provide a click event, but do not actually link to other content, should really be button elements because that's what they really are.
It can be styled like so:
<button style="border:none; background:transparent; cursor: pointer;">Click me</button>
And of course click events can be attached to buttons without worry of the browser jumping to the top, and without adding extraneous javascript such as onclick="return false;" or event.preventDefault() .
Solution 3:
You should really put a real link in there. I don't want to sound like a pedant, but that's a fairly bad habit to get into. JQuery and Ajax should always be the last thing you implement. If you have a link that goes no-where, you're not doing it right.
I'm not busting your balls, I mean that with all the best intention.