Making a div element clickable in HTML

To make an element, for example a <div>, clickable in HTML, you can use the following code:

<div onclick="location.href='#';" style="cursor: pointer;">
</div>

We simply add the onlcick event and add a location to it. Then, additionally and optionally, we add a cursor: pointer to indicate to the user the div is clickable. This will make the whole div clickable.

 

Author Bio

Thank you for your interest in my blog! On this miniblog, I write mostly short (technical) blog posts that might interest other people. Read more about me or feel free to contact me.

 

6 thoughts on “Making a div element clickable in HTML

  1. Lovely. Thanks, Thomas, the tip is much appreciated. I’m rebuilding my web site and have been scratching my head over this, and searching the web, for a solution, for hours. It seems that there are crowds of ‘coders’ infesting cyberland whose main aim in life is to make things more complicated than is necessary.

    Regards,
    John

  2. The issue I’m having is that although this work for the div, if you have some text in the div (link a card-type element with a title) and you want the same behavior no matter whether the mouse clicks the div itself or the text this solution doesn’t cover it. But I can’t imagine you have to rig up the text span or whatever with the exact same click functionality do you? Isn’t there a way to just say- apply all click functionality for a to its children?
    Anything helps.
    Thanks.

  3. Sorry – lots of typos in my above comment. I’m just asking if there is a way to apply the same event listener to a whole div including any html elements that might be inside that div, so if a div has an image and a header and some text in it, no matter where you click in the div it will all act as a link, including on the image or text.
    A little soundboard site I made yesterday has this problem. If you click the div it works, but if you click the text it doesn’t.
    Url to soundboard site: http://100days100projects.com/day14-larryDavidSoundBoard/index.html
    Thanks again.

Leave a Reply

Your email address will not be published. Required fields are marked *