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.
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
thanks bro, this is a great site
Saved my day! ^_^
Thank you for this!
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.
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.
Nic vido
Thank you. Really helpful.
Can you tell me please how i will open the link in a new tab using your code?
Hello Saimon
thanks for your comment!
In order to make a div clickable and open it in a new tab, you could try something like the following:
onclick=”window.open(‘#’)
You should then replace # with the URL that needs to be opened in a new tab in the user’s browser.
Kind regards
Thomas
I’m forced to change my SVGs through CSS only. Is there a way to make an SVG into a clickable link using only the element?
Thats why I don’t go to stack overflow, nice and easy awnser.