Alex Rivera | Logout

How to make an anchor tag refer to nothing?

Asked 2009-05-29T07:21:05.703
190

I use jQuery, I need to make some anchor tags perform no action.

I usually write it like this:

<a href="#">link</a>

However this refers to the top of the page!

Edit
Report

1 Answer

17

This answer should be updated to reflect new web standards (HTML5).

This:

<a tabindex="0">This represents a placeholder hyperlink</a>

... is valid HTML5. The tabindex attribute makes it keyboard focusable like normal hyperlinks. You might as well use the span element for this as mentioned previously, but I find using the a element more elegant.

See: https://w3c.github.io/html-reference/a.html
and: https://html.spec.whatwg.org/multipage/links.html#attr-hyperlink-href

Some JavaScript to respond to clicking the link (or tabbing to the link, pressing Enter):

<script type="module">
    let linkActivated = e => {
        alert(`Event triggered: ${e.type}`);
    };

    document.querySelectorAll('a:not([href])').forEach(el => {
        el.addEventListener('keydown', e => {
            if (e.key == 'Enter') {
                linkActivated(e);
            }
        });

        el.addEventListener('click', linkActivated);
    });
</script>
answered 2013-01-10T12:57:32.927

Your Answer