How to make a clickable banner

420 views javascript
3

I have a div and there is a link inside. When I click on a div, it should open the link (ex: google.com) but when I click the button it should open another link.

<div class="sc-banner">
    <a href="#" target="_blank">Button</a>
</div>
$(".sc-banner").click(function (event) {
    event.stopPropagation();
    window.open ('http://google.com', "_blank");
});

answered question

You've shown the click handler for the div, so what's the question?

The problem is that when I click on the button, the link (google) opens at the same time.

and how to implement correctly? so that the links work separately?

try adding click handler to the button as well with another link.

@A.Meshu no, that's something completely different.

1 Answer

2

The issue is because the click event from the a is propagating up the DOM and firing the click handler on the div.

You can fix this in a couple of ways. Firstly, check what the event target was in the div handler:

$(".sc-banner").click(function(e) {
  e.stopPropagation();
  if (e.target.tagName !== 'A')
    window.open('http://google.com', "_blank");
});

Alternatively you could add another event handler to the a which calls stopPropagation():

$(".sc-banner").click(function(e) {
  e.stopPropagation();
  window.open('http://google.com', "_blank");
});

$(".sc-banner a").click(function(e) {
  e.stopPropagation();
});

posted this

Have an answer?

JD

Please login first before posting an answer.