I have a set of clickable identifiers on my page. About hundred, like 'cat1', 'cat2', 'dog1', 'dog2', 'dog3' etc. Then I have a function IDClick(id) {}
I need those identifiers clickable in HTML, to achieve that I used <a>
tag with onclick
<a onclick=IDClick(id)>id</a>
now it works, but the cursor will not change when it is hovered over the clickable element.
So I try to add href=#
<a href=# onclick=IDClick(id)>id</a>
Now the cursor is OK, but when I click the item, the URL in the browser location bar will change. This is not desired.
How to get the mixed behavior?
I do not need underline as well.
You should add [role="button"] as semantically the <a> tag is no longer being used as a link, but as a button.
Yes, it is valid to use the anchor tag without a href attribute. If the a element has no href attribute, then the element represents a placeholder for where a link might otherwise have been placed, if it had been relevant, consisting of just the element's contents.
In the href also serves keyboard navigation without the mouse. If your website is required to function without Javascript then you have to use onclick so the href can have a link in it. Adding the action in a separate Javascript file fails to keep code & data bound tightly.
This is a type of JavaScript link - the onclick attribute defines a JavaScript action when the 'onclick' event for the link is triggered (i.e. when a user clicks the link) - and there is a URL present itself in the onclick attribute.
You need to stop the browser from doing it's default action.
<a href="#" onclick="IDClick(id);event.preventDefault();">id</a>
When you click on a link, the default action is to go to that address. event.preventDefault();
prevents the browser from doing the default action.
This is a significantly better solution for accessibility. Quoting @aij's comment above: "using CSS makes it look ok, but still leaves it inaccessible from the keyboard (ie, tab will never focus the link)".
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With