Suppose I have a clickable complex div
element structure which links to another page as follows. This is the thing that is being achieved currently on click.
On click (css :active state) change the background color inside <a>
tag and redirect to other page.
I am wondering whether this conforms to HTML5 validation or consider as a best practice compared to wrapping it with a div
and using JavaScript to manage the link redirect and background color change on click.
To me, the first approach seems to be much cleaner and straight forward.
I believe this is a common issue face by a lot of web developers but I am not sure whether there is an existing best practice solution for this.
1) Maintain as this
<a href="page1.html">
<div>
<!-- complex layout -->
</div>
</a>
2) Omit the <a>
tag and manage background color during click event and redirect using JavaScript
<div id="#redirectLink" data-link="page1.html">
<!-- complex layout -->
</div>
HTML5, you can wrap a DIV
inside an A
anchor
<a href="page1.html">
<div>
<!-- complex layout - WITHOUT ANCHORS OR BUTTONS -->
</div>
</a>
only if inside <!-- complex layout -->
you don't have another <a>
or Form-action elements like <button>
etc.
Otherwise you can do:
<div id="#redirectLink" data-link="page1.html">
<!-- complex layout -->
</div>
<script>
document.querySelectorAll("[data-link]").forEach( el => {
el.addEventListener("click", () => window.location.href = el.dataset.link);
});
</script>
or simply:
<div id="#redirectLink" onclick="window.location.href='page1.html';">
<!-- complex layout -->
</div>
but inline JavaScript is bad design since hard to maintain and debug, so prefer having it in your script files.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With