Make a Clickable Link With Onclick But Without Href=#

Make a clickable link with onclick but without href=#?

You can use CSS to force the cursor to change on hover of the clickable element:

.myClickableThingy {
cursor: pointer;
}

And then you can switch back to <span>s or whatever of element you were using before <a> tags.

<a> onclick not clickable without href

Add some text to <a> and it works:

.btn2 {cursor: pointer; }
<a class="btn2" onclick=alertbox();>Link</a>  <script>   function alertbox()  {        alert("alert box")}</script>

Anchor without href

A do-nothing link, that doesn't even jump:

<a href="javascript:void(0)">link</a>

Update: As linked document suggests (pointed out by Ambrosia), since void(0) returns undefined, it is better to actually write above code as:

<a href="javascript:undefined">link</a>

Unless, of course, undefined has been re-defined.

<a> script links without href="#"

<a> stands for anchor

If you include the [href] attribute on an <a> element, it is an anchor that points to a location, which means that you could go to a new page, a particular fragment of the current page (hence the # being called the fragment identifier), or a particular fragment of a new page.

<a> elements without an [href] attribute were historically assigned a [name] attribute, which could be used as the destination of the fragment identifier. Browsers later added support for linking to any item's [id] attribute, and this is now the preferred method for linking to a document fragment.

What does this mean for standalone <a> elements?

An a[href] element is a link (which is why they are matched with :link in css). links are clickable. An a element without the [href] attribute is otherwise just a placeholder for where a link might otherwise have been placed, and not clickable, nor are they in the tabbing order of the page.

If you want your links to be keyboard navigable which is important for accessibility (WAI-ARIA), you'll need to do one of the following:

  • change the element to <button type="button">
  • keep the [href] attribute
  • add [tabindex="0"] and one of [role="button"] or [role="link"] (and possibly some styling)

More information about the [role] attribute can be found in the Roles Model section of the WAI-ARIA docs.

Changing the markup

If you don't have a reason to keep the [href] attribute, you might as well be using a <button> element:

<button type="button">
^^^^^^^^^^^^^

The [type] attribute is used to make the element a generic button, otherwise <button> will default to [type="submit"], which may not be desirable as it could trigger form submission.

If you can't use a <button> (usually occurs when the inner markup must contain a <div>) you can fake a <button> using:

<div role="button" tabindex="0">Some clickable text</div>

You'll need to listen for keypress events and trigger click events for Enter and Space.

Keeping the markup

If you're keeping the <a> element and its [href] attribute, there are a number of options for its value.

A real link

E.x.

  • <a href="/some/location/for/users/without/js">
  • <a href="#document-fragment">

If you need to provide support for users with JS disabled, you might as well direct them to a page that performs equivalent functionality without JS.

By extension, this also includes providing document fragment links to link to the content within the same document. For example, a toggleable region may be marked up as:

<a href="#more" class="toggleable">Read More</a>
<div id="more">Lorem ipsum dolor sit amet</div>

So that with JS the region can be collapsed and expanded, and without JS the link will take the user to the appropriate content on the page.

A dud href

E.x.

  • <a href="#">
  • <a href="javascript:void(0)">
  • <a href="about:blank">

If you're preventing the default behavior behind-the-scenes in JavaScript, and you're not supporting users with JS disabled, you can use a "dud" href value to keep the link in the tabbing order and automatically enable Enter to trigger the click event. You should add [role="button"] as semantically the <a> tag is no longer being used as a link, but as a button.

<a href="#" role="button">Some clickable text</a>

How do I make links with no href attribute accessible?

To make a non-href <a> behave like an <a> (and be accessible), you'd have to add role=link, tabindex=0, style it to look like a real link, and add keyboard handler code to treat Return as a click.

role="link" isn't sufficient; a screenreader may report it as a link, but without tabindex="0" and appropriate visual styles, a sighted user won't be able to tab to it in the first place, and without a keyboard event handler, only mouse users will be able to click it. (Technically screenreader users typically have hotkeys to simulate a mouse click, but keyboard-only sighted users generally don't have that option, so don't rely on it.)

Alternatively, if (big if!) the crazy script you're using allows for it, you could try shimming a 'keyboard click source' (my terminology) <a> just inside the original one: so where you have:

<a>foo</a>

you replace it with:

<a><a class='shim' href="javascript:void(0)">foo</a></a>

(The class='shim' is only needed if you need to do the event stuff described later...)
You can do this in jQuery using something like: (borrowing from Jack's answer)

$("a:not([href])").wrapInner("<a class='shim' href='javascript:void(0)'></a>")

How this works is that the inner newly-added <a ...> has a href, so it is exposed as a link and is tabbable. More importantly, if a user tabs to it and presses return, the default A behavior converts that keyboard input into a click event. This specific A has a href that returns undefined/void(0), so no actual navigation happens, but the click event will still bubble up to the original A, which gets to act on it.

(This is a neat pattern for allowing some parent element - often a DIV or similar - to handle click events, adding a child tabbable A that can source click events from keyboard gives you UI that's both mouse and keyboard usable.)

The big caveat here is that it assumes that your original script doesn't care about the target of the event. If that script does check this, it will get confused when it sees click events coming from the shim A's rather than the original As. One way to get around this is to capture and re-raise the event, which can be fiddly, and may only work on recent browsers - eg using something like:

// 'shim' class used so we can do this:
$("a.shim").click(function(e) {
e.preventDefault();
e.stopPropagation();

// the following works if listener using jQuery or is setting onclick directly, otherwise...
// $(e.target).parent().click();.

// More general way to raise events; may need alternate for IE<9
var e2 = document.createEvent("UIEvents");
e2.initUIEvent("click", true, true, window, 1);
e.target.parentNode.dispatchEvent(e2)
});

How can I disable HREF if onclick is executed?

You can use the first un-edited solution, if you put return first in the onclick attribute:

<a href="https://example.com/no-js-login" onclick="return yes_js_login();">Log in</a>

yes_js_login = function() {
// Your code here
return false;
}

Example: https://jsfiddle.net/FXkgV/289/

Use onCLICK but fallback to HREF if right-clicked

You can prevent the default anchor click behaviour if your onclick event returns false:

<a href="important.html" onclick="window.open('important.html', '_blank', 'width=900,height=600'); return false">link</a>

Valid to use <a> (anchor tag) without href attribute?

The <a>nchor element is simply an anchor to or from some content. Originally the HTML specification allowed for named anchors (<a name="foo">) and linked anchors (<a href="#foo">).

The named anchor format is less commonly used, as the fragment identifier is now used to specify an [id] attribute (although for backwards compatibility you can still specify [name] attributes). An <a> element without an [href] attribute is still valid.

As far as semantics and styling is concerned, the <a> element isn't a link (:link) unless it has an [href] attribute. A side-effect of this is that an <a> element without [href] won't be in the tabbing order by default.

The real question is whether the <a> element alone is an appropriate representation of a <button>. On a semantic level, there is a distinct difference between a link and a button.

A button is something that when clicked causes an action to occur.

A link is a button that causes a change in navigation in the current document. The navigation that occurs could be moving within the document in the case of fragment identifiers (#foo) or moving to a new document in the case of urls (/bar).

As links are a special type of button, they have often had their actions overridden to perform alternative functions. Continuing to use an anchor as a button is ok from a consistency standpoint, although it's not quite accurate semantically.

If you're concerned about the semantics and accessibility of using an <a> element (or <span>, or <div>) as a button, you should add the following attributes:

<a role="button" tabindex="0" ...>...</a>

The button role tells the user that the particular element is being treated as a button as an override for whatever semantics the underlying element may have had.

For <span> and <div> elements, you may want to add JavaScript key listeners for Space or Enter to trigger the click event. <a href> and <button> elements do this by default, but non-button elements do not. Sometimes it makes more sense to bind the click trigger to a different key. For example, a "help" button in a web app might be bound to F1.



Related Topics



Leave a reply



Submit