top | item 14706034

Ask HN: Href=“#” VS href=“JavaScript:;”

2 points| optikals | 8 years ago | reply

Sorry for my silly question, can you tell me if there's a difference between href="#!" and href="javascript:;"

and which one it's better to use on the links with JavaScript attached to them (nothing else, JS only).

I know it's not the correct use, it should be a "button", but I really need to use <a>.

Thank you.

4 comments

order
[+] twobyfour|8 years ago|reply
Neither, put a real URL in there so people can a) use your site without JS and b) open links in new tabs. Use e.preventDefault().

If you can't put a URL in it, use a different element. Why can't you use <button>? It's definitely the correct element for something that takes an action. In a pinch, fall back on <span>?

[+] optikals|8 years ago|reply
Thank you for your help, Sir.
[+] savethefuture|8 years ago|reply
There is no "correct" way to do anything in web, I would say its generally best practice or personal preference. I tend to use # and target the tag with a data attribute and use e.preventDefault(). #! from what I've seen is used for handling client-side routing. Any tag can be used as a button in javascript, as long as you target it correctly.
[+] optikals|8 years ago|reply
Thank you, Sir! And please, save the Future.