1

I have a page with a bunch of tables that all share a class. I'd like to be able to add a click function to each of them using GreaseMonkey. The script runs but only the first table ever seems to work. Clicking on it causes a message to be logged, the others do nothing.

Here's my GreaseMonkey script:

$(document).ready(function(){
    $('.data').click( function() {
            console.log( "clicked" );
            return false;
    });
});

Sample HTML:

<div>
    <table class="data" id="125232">
        ...
    </table>
    <table class="data" id="252123">
        ...
    <table>
    <table class="data" id="125234">
        ...
    </table>
</div>

So in this case, only the table with id 125232 has a working click function.

Tainze
  • 11
  • 1
  • Are those tables are created during run time.? – Rajaprabhu Aravindasamy Dec 20 '13 at 18:28
  • [Can't reproduce](http://jsfiddle.net/H2anD/). – vcsjones Dec 20 '13 at 18:29
  • There is definitely some content loading that occurs on that page but I can't tell if the tables themselves are being created dynamically. Do you have a suggestion for a fix assuming they are? – Tainze Dec 20 '13 at 18:31
  • vcsjones, I probably should have said I'm aware of that. I pasted this directly into the console and it works. It's only a problem when working with GreaseMonkey. – Tainze Dec 20 '13 at 18:32

1 Answers1

4

Use delegated events: (jQuery docs)

$('body').on('click', 'table.data', function(e){
    console.log('Clicked!');
});
jry
  • 41
  • 1
  • This appears to be working how I expect! Thank you very much! I don't have enough rep to upvote, but hopefully others can help me out in that front. – Tainze Dec 20 '13 at 18:36
  • delegated events don't get enough press coverage. jQuery kind of makes it hard to understand what they really do -- but they are WONDERFUL. – Jeremy J Starcher Dec 21 '13 at 06:43