Search code examples
javascriptjqueryajaxhovertablerow

why Javascript function wont apply to element?


I have this structure for one of my pages:

head  
    script  
   /script  
/head  
body  
    table1  
    table2  
/body  

here is the javascript:

<script type="text/javascript">
    $( function() {
      $('tr').click( function() {
         $(this).parents('table').find('tr').each( function( index, element ) {
              $(element).removeClass('selected');
         } );
         $(this).addClass('selected');
         $(this).removeClass('normal');
      } );
    } );
    $( function() {
      $('tr').hover( function() {
         $(this).addClass('highlight');
         $(this).removeClass('normal');
      } );
    } );
    $( function() {
        if($('tr').hasClass('selected')) {
        }
        else {
          $('tr').mouseout( function() {
             $(this).removeClass('highlight');
          } );        
        }
    } );
</script>

table1 is generated by loading the page, while table2 is generated by clicking on any row of table1, using Ajax.

upon click or hover, the script adds some classes to tr (table rows) so I can style them (change background color)

the script applies to table1 rows and adds classes, but does not apply to table2 rows!

any help would be appreciated.


Solution

  • These events only apply to elements that exist when the page is loaded. You need to use "live" events for them to affect the AJAX-loaded table (table2).

    For this, you can use jQuery's .on:

    $(function(){
        $(document).on('click', 'tr', function() {
             $(this).parents('table').find('tr').each( function( index, element ) {
                  $(element).removeClass('selected');
             } );
             $(this).addClass('selected');
             $(this).removeClass('normal');
        });
        $(document).on('hover', 'tr', function() {
             $(this).addClass('highlight');
             $(this).removeClass('normal');
        });
        $(document).on('mouseover', 'tr', function(){
            if(!$(this).hasClass('selected')){
                $(this).removeClass('highlight');
            }
        });
    });
    

    Note: Instead of document, you can use the highest parent of both tables (as long as it stays in the DOM).

    UPDATE: The if($('tr').hasClass('selected')) { only ran when the DOM loaded. Put that check inside the event.

    P.S. You can combine all those $( function() { together.