I want to make HTML elements clickable using Javascript. Here’s what I have:
<div class="link">
<a href="http://example.com">
</div>
<script>
$('.link').click(function(){
if(link=$(this).find('a').attr('href'))
window.location.href=link;
});
</script>
This works, but I’m wondering if there’s a better way to do this. Thanks!
While your example works, it is neither semantic nor clean. You can’t right click the div to copy the link location or open in new tab, or middle click it etc. There’s nothing stopping you from setting an anchor to
display: blockto act like a div and then putting all sorts of elements inside theatag itself. That’s the semantic way to do it – let the browser handle the native function of a link.