KevinUK
KevinUK

Reputation: 5153

How to reduce the number of click events with JQuery?

I have a table with 100s of rows and each row has its own click event:

$('#scorecard-table tbody > tr.accordion').on('click', function (event) {}

I want to get this down to one click event, I thought this would do it?

$('#scorecard-table').on('click', 'tbody > tr.accordion', function (event) {}

I assumed this would assign a single click event on the table itself instead of an event per row?

The second version seems to have just as many events as the first version. What am I doing wrong?

Upvotes: 2

Views: 258

Answers (4)

devanand
devanand

Reputation: 5290

I found the following explanation on jquery

http://api.jquery.com/on/

In addition to their ability to handle events on descendant elements not yet created, another advantage of delegated events is their potential for much lower overhead when many elements must be monitored. On a data table with 1,000 rows in its tbody, this example attaches a handler to 1,000 elements:

$( "#dataTable tbody tr" ).on( "click", function() {
  alert( $( this ).text() );
});

A delegated-events approach attaches an event handler to only one element, the tbody, and the event only needs to bubble up one level (from the clicked tr to tbody):

$( "#dataTable tbody" ).on( "click", "tr", function() {
  alert( $( this ).text() );
});

That should answer your question?

Upvotes: 1

Sami Racho
Sami Racho

Reputation: 79

You can add an event listener only to the table, and check if the user clicked on a row. (It will work even if you add more rows dinamically)

$('#myTable').on("click", function (e) {

    if(e.target.tagName == "TD"){
        alert(e.target.parentNode.id);

        // if you want the jQuery row object
        // var rowClicked = $(e.target.parentNode)
    }
});

JsFiddle example: http://jsfiddle.net/utVzx/2/

Upvotes: 0

Rohan Kumar
Rohan Kumar

Reputation: 40639

The second one is fast as tested on jsperf

$('#scorecard-table').on('click', 'tbody > tr.accordion', function(event) {
   // your code
});

As above will selects $('#scorecard-table') first then bind click event to tbody > tr.accordion

And in the first-one

$("#scorecard-table tbody > tr.accordion") evaluates from right to left - i.e. first it finds all of the tr.accordion rows in the page and then narrows it down to those under #scorecard-table tbody

Here you can test the performance

Read Efficient-jquery-selector and see performance of child selectors

Upvotes: 0

Chris Dixon
Chris Dixon

Reputation: 9167

Not 100% sure what you're trying to do here... if you're wanting to do the entire table (just the one event) why not just do:

$('#scorecard-table').on('click', function (event) {}

Doing it this way, though, you wouldn't be able to detect which row was clicked unless you fiddled about with the mouseX / mouseY. You're best off with the singular click events like you have now.

Upvotes: 0

Related Questions