Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery div onclick to click an href inside the div

Tags:

jquery

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?

like image 850
Al. Avatar asked Oct 23 '09 19:10

Al.


People also ask

Can I add onclick to href?

How to make this a tag working with href and onClick? The default behavior of the <a> tag's onclick and href properties are to execute the onclick , then follow the href as long as the onclick doesn't return false , canceling the event (or the event hasn't been prevented).

Can we use Onclick in div?

We can bind a JavaScript function to a div using the onclick event handler in the HTML or attaching the event handler in JavaScript. Let us refer to the following code in which we attach the event handler to a div element. The div element does not accept any click events by default.

How do you trigger a click element?

The HTMLElement. click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events.

Can I use onclick on anchor?

First, you have to block href call URL if don't want to open the tab/window or other operations. You can call a function in 2 ways using the href or onclick attribute in the HTML tag.


1 Answers

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;
});
like image 62
Stefan Kendall Avatar answered Nov 11 '22 18:11

Stefan Kendall