Al.
Al.

Reputation: 2872

jQuery div onclick to click an href inside the div

I have the following HTML:

<table class="products">
  <tr>
    <td>Product description probably goes here</td>
    <td><a href="#">more information</a></td>
  </tr>
</table>

To make it a bit sexier for Javascript-enabled browsers I've added this jQuery (1.3.2):

$(document).ready(function(){
  $('table.products tr').click(function(){
    $(this).find('a').click();
    return false;
  });
});

But I think it gets into an infinite loop or something. Safari shows this:

RangeError: Maximum call stack size exceeded. jquery.min.js:12

Can anyone please offer a workaround or better way?

Upvotes: 7

Views: 22020

Answers (7)

Brad
Brad

Reputation: 15577

mine was a list item in a dropdown so i wanted the event to keep bubbling so the dropdown would be closed. this is the solution i used:

$('div#outer').click(function (e) {
   if (e.target == e.currentTarget) // prevents bubbled events from triggering
      $($(e.currentTarget).children()[0]).trigger('click');
});

Upvotes: 0

Zack
Zack

Reputation: 1703

This is a pretty late answer, but I found this to be a very short and simple solution:

$('ul li').bind('click', function() {
    location = $(this).find('a').attr('href');
});

Upvotes: 4

yannickoo
yannickoo

Reputation: 126

I had the same problem and I solved it with adding e.stopPropagation(); to the a on click:

$(document).ready(function() {
  $('table.products tr').bind('click', function() {
    $(this).find('a').click();
    return false;
  });

  $('table.products tr a').bind('click', function(e) {
    e.stopPropagation();
  });
});

Upvotes: 6

Vojtech Bulant
Vojtech Bulant

Reputation: 11

Simply try to use bind('click') instead of click() shortcut, it worked for me in almost same case.

Upvotes: 1

andres descalzo
andres descalzo

Reputation: 14967

$(document).ready(function(){
  $('table.products tr').click(function(e){
    e.stoPropagation(); // for stop the click action (event)
    $(this).find('a').click();
    return false;
  });
});

Upvotes: -2

Shawn
Shawn

Reputation: 19813

First, I would console.log($(this).find('a')) and make sure it is the appropriate link. Next, I believe the click event is not what you want on the a element. I think you just want: var a = $(this).find('a'); if (a) document.location.href = a.attr('href');

My JavaScript is pretty weak though : )

Upvotes: 0

Stefan Kendall
Stefan Kendall

Reputation: 67832

The problem here is that a lies within the tr. Ergo, when the a click() method is triggered, the event bubbles to the tr containing it, creating the recursive loop you mentioned. Rather than call .find('a').click(), have both a and tr use the same click method.

$('tr, a').click(function(){
   //dostuff
   return false;
});

Upvotes: 9

Related Questions