0

In my code, I want to click on the div and have it fire a click() on the specified element ID, however I'm getting this recursion error instead, like it's in an infinite loop.

function clickLink(id) {
  $('#' + id).click();
}
.theDiv {
  border: 1px solid red;
  width: 200px;
  height: 200px;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

click the div, but not on the link
<div class="theDiv" onclick="clickLink('linkId')">
  <a href="http://www.google.com" id="linkId">i am a link</a>
</div>
Daniel Williams
  • 2,195
  • 7
  • 32
  • 53
  • 1
    your problem is the bubbling check this: https://medium.com/@vsvaibhav2016/event-bubbling-and-event-capturing-in-javascript-6ff38bec30e Aside from that, I have the feeling that you can accomplish wherever you are looking for without doing this. Try to style the `a` with `display:block` – Raúl Martín Sep 12 '18 at 01:43
  • I explained what I'm wanting to achieve. Have an onclick event on the div that fires the link inside it. – Daniel Williams Sep 12 '18 at 02:00
  • @DanielWilliams Have you tried my updated answer? I was able to recreate your problem and solve it. – dustytrash Sep 12 '18 at 02:01
  • Yes it works, thanks – Daniel Williams Sep 12 '18 at 02:02

3 Answers3

2

This is in fact an infinite loop because of event bubbling. Events that occur on the child elements will bubble up to parents. In your case click that occurs on the a#linkId will bubble to the parent div and trigger the onclick handler ("clicking" the a#linkId again).

vicbyte
  • 3,690
  • 1
  • 11
  • 20
  • *free hint:* what OP is trying to achieve is a click router. So that wherever you click, inside the div, it does trigger the anchor click. For this to happen, the cleanest way might actually be to wrap the div inside the anchor. But otherwise, it is very well possible to look at the event.target and decide if the routing should occur or not. – Kaiido Sep 12 '18 at 01:55
0

Try this instead:

function clickLink(id) {
    $('#' + id)[0].click();
}

There may still be recursion, but the problem is your click function isn't working. Since we're leaving the page (clicking a link to google.com), it doesn't really matter.

For explanation on the click event see Roman Starkov's comment: How to trigger a click on a link using jQuery

dustytrash
  • 1,568
  • 1
  • 10
  • 17
0

Try to use the trigger from jquery

function clickLink(id) {
  $('#' + id).trigger(”click”);
}