John Blythe
John Blythe

Reputation: 603

Anchor trigger or click event issues when applying to parent div

I've been browsing through several posts and none of them have quite helped as of yet.

I have some fancy buttons setup like so:

<div class='orange-btn'>
<a href="url.html">BLah blah</a>
<span>Meta text</span>
</div>

I need a click event on the div (or any children, ie <span>) to kick into the anchor and cause a click() function.

As of now i get the 'maximum call stack size exceeded' error or an error that simply says <error before my browser tab completely crashes.

Thanks for any assistance.

Upvotes: 1

Views: 244

Answers (3)

Pevara
Pevara

Reputation: 14308

Why do you need the div in the first place? Why not just do something like this:

<a href="url.html" class="orange-button">
  <span class="label">Bla Bla</span>
  <span class="meta">Meta data</span>
</a>

If you set the .orange-button to display as block, you should get the exact same effect. Something like this:

.orange-button {
  display: block;
  /* the other styles that where on your div */
}
.orange-button .label {
  /* the styles that where on your a */
}
.orange-button .meta {
  /* the styles that where on your span */
}

I am a strong believer of not using any js unless it is really necessary. There are still some users out there that have js disbaled and they deserve the same experience on your site...

Upvotes: 0

AbdElrhman
AbdElrhman

Reputation: 52

try this

 $('div').children().click(function (){
  alert();
 });

and here you need to trigger the a click

Upvotes: 0

Blazemonger
Blazemonger

Reputation: 92983

That's because of event bubbling -- after you click on the link, that click will propagate up to the div, which triggers a click on the link, ad infinitum.

Add the following to solve this:

$('a').on('click',function(e) {
   e.stopPropagation();
});

(Use $(document).on('click','a',function(e) {...}); if your links are added dynamically.)

Upvotes: 1

Related Questions