Just a matter of curiosity, I know it will work, but is it standard-compliant?

I want to use <a> tag with onclick instead of href action, is it "correct"?

3 answers

2
points

Yes, you can have an anchor tag without a href. After all, anchors are also used to indicate positions in a page. cfr: http://www.w3schools.com/tags/att_a_name.asp

Answered almost 3 years ago by Joeri Hendrickx
w3d 25
1
point

Use both. If, in your onclick event you are linking to another resource (eg. a popup of information) then you should still provide a suitable URI in the HREF attribute for accessibility (As danwellman suggests: return false; in the onclick event to prevent the HREF from being followed). It should still be accessible to those with JavaScript disabled - which includes search engines.

The problem with using href="#" is that the page scrolls up to the top if it is followed (if JavaScript is disabled, if the user middle clicks or right mouse and open in new tab). You could alternatively specify href="javascript:void(0);" (more JavaScript!?) which prevents the open in new tab option in some browsers and avoids the page being scrolled to the top and avoids the need to return false; in your onclick event - but this is still not ideal.

So, best to use both if possible. (But yes, it is still valid HTML to omit the href attribute.)

Answered almost 3 years ago by w3d
danwellman 5600
0
points

Some browsers (ahem, IE) fail to render the pointer cursor on links that don't have href attributes.

In practice I find it best to include the href with a hash symbol, <a href="#">JS Button</a> and either return false; or use event.preventDefault(); from the handler rather than omitting the href entirely...

Answered almost 3 years ago by danwellman