How to fire links with jQuery?

I want to fire a link if the div around gets clicked.

This is the general logic:

$("div").click(function() {
  $("div a").click();
});
div {
  background-color: yellow;
  padding: 20px;
  margin: 10px;
}

div:active {
  background-color: blue;
}

div a {
  pointer-events: none;
  text-decoration: none;
  color: inherit;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div><a href="https://en.wikipedia.org/wiki/London">London</a></div>
<div><a href="https://en.wikipedia.org/wiki/London">Paris</a></div>
<div><a href="https://en.wikipedia.org/wiki/London">Almaty</a></div>

Unfortunately, it does not work. I think I would need the different href as variable or something like that. For now, probably all links would be fired at the same time, and not only the belonging one.

How is it possible to do that?

Would be thankful for help! <3

Answer

If your code would work, you would end up clicking every link that is in side of a div. It is not going to just click the link in the div you are in. So first thing you need to do is select the link in the div you clicked.

After that, you need to trigger click on the DOM element, not the jQuery object. When you trigger it on the jQuery object, it only triggers the click event listeners you bound to it.

$("div").click(function() {
  $(this).find("a").get(0).click();
});
div {
  background-color: yellow;
  padding: 20px;
  margin: 10px;
}

div:active {
  background-color: blue;
}

div a {
  pointer-events: none;
  text-decoration: none;
  color: inherit;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div><a href="https://en.wikipedia.org/wiki/London">London</a></div>
<div><a href="https://en.wikipedia.org/wiki/London">Paris</a></div>
<div><a href="https://en.wikipedia.org/wiki/London">Almaty</a></div>

Or just make the anchor take up the whole div so you do not need JavaScript at all.

div {
  background-color: yellow;
  margin: 10px;
}

div:active {
  background-color: blue;
}

div a {
  padding: 20px;
  display :block;
  width: 100%;
  height: 100%;
  text-decoration: none;
  color: inherit;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div><a href="https://en.wikipedia.org/wiki/London">London</a></div>
<div><a href="https://en.wikipedia.org/wiki/London">Paris</a></div>
<div><a href="https://en.wikipedia.org/wiki/London">Almaty</a></div>

Leave a Reply

Your email address will not be published. Required fields are marked *