Make html elements clickable with javascript
First appeared on mobifreaks.com · Updated
On touch phones of 2012, other than the iPhone and Android, small link targets were hard to hit. On my Samsung Jet 2, I sometimes had to tap a heading twice. Making the whole block clickable fixed that.
The 2012 way
One line of JavaScript sends the browser to a new address:
window.location = 'URL';
Put it in an onclick and any element becomes clickable:
<div onclick="window.location = 'https://example.com/post'">
<!-- Some data -->
</div>
In WordPress, inside the loop, the URL came from the_permalink(). I also added a note to keep a real link inside the block, so search engines could still follow it.
Why I wouldn't do that now
A div with onclick only works with a mouse or finger. Keyboard users can't tab to it, screen readers don't announce it as a link, and people can't middle-click or long-press to open it in a new tab.
The way I'd do it today
Use a real link, then stretch its clickable area over the whole card with CSS. No JavaScript needed.
<article class="card">
<h2><a href="/posts/responsive-data-tables-jquery">Responsive Data Tables with jQuery</a></h2>
<p>Converting a table into labelled cards on small screens.</p>
</article>
.card { position: relative; }
.card a::after {
content: "";
position: absolute;
inset: 0;
}
.card:has(a:focus-visible) {
outline: 2px solid currentColor;
outline-offset: 4px;
}
- The link's
::aftercovers the card, so a tap anywhere on it follows the link. - It is still one real link: keyboard, screen readers, middle-click and "open in new tab" all work.
:has()puts the focus ring around the whole card when the link is focused.- If the card has other links or buttons, give them
position: relativeso they sit above the overlay and stay clickable.
In WordPress
<article class="card">
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<?php the_excerpt(); ?>
</article>