Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS - Make a div "clickable"

I'd like to know how i can render a div clickable (like a link, with the small hand when i go over with the mouse).

I have some elements like this:

<div class="teamSelector">Some</div>

With this jQuery:

$('.teamSelector').click(function() { 
    // some functions
});

Cheers

like image 779
markzzz Avatar asked Dec 14 '10 17:12

markzzz


People also ask

Can I make a div a link?

You can't make the div a link itself, but you can make an <a> tag act as a block , the same behaviour a <div> has. You can then set the width and height on it.

Can I use onclick on a div?

We can bind a JavaScript function to a div using the onclick event handler in the HTML or attaching the event handler in JavaScript. Let us refer to the following code in which we attach the event handler to a div element. The div element does not accept any click events by default.


4 Answers

You've already made it clickable in your example. If you would like it to "look" clickable, you can add some CSS:

.teamSelector { cursor: pointer; } 

Or continuing with jQuery:

.click(function() { do something }).css("cursor", "pointer"); 

Here is the W3 schools reference for the cursor property.

like image 93
jthompson Avatar answered Oct 02 '22 21:10

jthompson


The css for it is:

.teamSelector
{
  cursor: pointer
}

You can also add hover effects, but I'm not sure if :active will work cross-browser.

If you need something to be clickable, you're better off using a button or a element and styling that. You can always prevent the default action with javascript. The reason it's better is for accessibility so that users with screen readers know that there's something to interact with.

Edit to add: When you tab through a page, you can hit the space bar to click an element. This will not work the same on non-interactive elements, so anyone using that functionality will not be able to use whatever it is you're making.

like image 20
zzzzBov Avatar answered Oct 02 '22 21:10

zzzzBov


this question is pretty old but needs some additions:

if you want to wrap component with pointer-based user interaction, you should prefer button element instead of a div(you can still display it block).

<button class="teamSelector" tabindex="1">Some</button>

styles:

.teamSelector{
    user-select: none; // this sets the element unselectable, unlike texts
    cursor: pointer; // changes the client's cursor
    touch-action: manipulation; // disables tap zoom delaying for acting like real button
    display: block; // if you want to display as block element
    background: transparent; //remove button style
    border: 0; //remove button style
}
like image 24
mkg Avatar answered Oct 02 '22 22:10

mkg


Can't you just, y'know, make it a link and style it? It would be easier and accessible.

like image 41
Piskvor left the building Avatar answered Oct 02 '22 22:10

Piskvor left the building