Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 214
exebook Avatar asked Nov 23 '13 17:11

exebook


People also ask

How do you make a link without using href?

You should add [role="button"] as semantically the <a> tag is no longer being used as a link, but as a button.

Can I use a tag without href?

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.

What is the difference between href and onclick?

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.

Can Onclick be a link?

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.


2 Answers

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)".

like image 60
Robbie Wxyz Avatar answered Sep 20 '22 11:09

Robbie Wxyz


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.

like image 43
beejay Avatar answered Sep 20 '22 11:09

beejay