How can I get an image to have it's own hyperlink that is inside of a clickable div?

<div id="clickable" onclick="window.open('http://www.daniweb.com');return false;">

  <p>I love clickable images!</p>
    <a href="http://www.google.com"><img src="someimage.png" /></a>
  <p>too bad they don't click in a clickable div</p>

</div>

If I try the above then the DIV is always getting the click, never the image in the div. I can click the image, but the link for the div is what opens. Removing the return false does not help either.

Dani AI

Generated

Good pickup by — the inner image/link can be made to work, but the root cause is event bubbling: a click on the image will bubble up and trigger the parent div's click handler. Two safe, practical approaches follow: stop the event from bubbling, or change the markup so interactive elements aren’t nested.

A minimal, unobtrusive-JS fix is to attach a click listener to the inner anchor that calls event.stopPropagation() so the parent’s handler never runs:

<!-- structure kept simple; URLs are placeholders -->
<div id="clickable">
  <a href="https://example.com/image-target"><img src="someimage.png" alt=""></a>
  <!-- other content -->
</div>

<script>
var container = document.getElementById('clickable');
var inner = container.querySelector('a');

container.addEventListener('click', function () {
  window.open('https://example.com/container-target');
});

inner.addEventListener('click', function (e) {
  e.stopPropagation(); // prevents the container's click handler from firing
  // allow the browser to follow the inner link normally
});
</script>

Better long-term options and cautions: avoid making a non-semantic div the primary clickable element — use an <a> or <button> for proper semantics and keyboard focus. Never nest anchors; if both the whole panel and a sub-item must be links, restructure (place the small link outside the big link or present a separate CTA). Test keyboard navigation (Tab/Enter) and touch devices, and prefer addEventListener over inline handlers for maintainability.

Recommended Answers

All 2 Replies

I thought I tried that one, but initial tests seem to be that it works.

Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.