Search code examples
javascriptjqueryhtmlhref

Should I use on click instead of href?


I have few items in my navigation bar side and horizontal. Each item holds the link for different page. I have read few articles about href attributes. There is a lot of different opinions on what should be used especially in HTML5 since href is not required. I would like to hide the link if possible. One of the options is to use onClick function. Also there is big debate on if there should be javascript or # sign. For example:

Option 1

<a href="#" onclick="someFunction(e)"></a>

or Option 2

<a href="javascript:void(0);" onclick="someFunction(e)">

I was wondering if this is the best way to approach this. Also I saw few options where JQuery is involved but I'm not sure if that would be the best option. if anyone can help with this please let me know. I just want to use something that is well tested and will be a long term solution. Thanks in advance.


Solution

  • If you are actually linking to another HTML page with a URL... then use a link element and an href.

    If you are in some framework and changing a route or view - or triggering some event - it's up to you. You can use buttons or any element or an <a> if you want, but you have a ensure to prevent the default behaviour of the link.

    It sounds like your question is not between href or none - but between link or something else.

    regular link

    <a href='http://sheriffderek.consulting' target='sheriff'>link</a>
    

    A fallback link for non-javascript sites? (not likely in 2017 unless you are a public library or something)...

    <a href='http://sheriffderek.consulting' onclick='someFunction(e)'>js view trigger with fallback link</a>
    

    another element

    <button onclick="someFunction(e)">button</button>
    

    Also - it depends on the framework. I believe Angular just says to use a link but leave off the href.