0

I have a simple jQuery collapsible table, where the header row is the trigger to toggle the data i want to show/hide.

What I'm after is to have an image within the header row and use this as the trigger, rather than the row itself.

Here is an example: http://jsfiddle.net/RDybT/

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>

<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type='text/javascript'>
    $(document).ready(function() {
        $('#trigger_1').click(function () { 
          $('#toggle_1', $(this).parent()).toggle();
       });
    $('#trigger_2').click(function () { 
          $('#toggle_2', $(this).parent()).toggle();
       });
     });
</script>

</head>

<body>
<img src="http://cdn5.iconfinder.com/data/icons/super-mono-reflection/blue/toggle-expand_blue.png" id="trigger_1"/>
<table border="2" cellpadding="2" cellspacing="2">
    <tr>
        <th>Header </th>
    </tr>
    <tr id="toggle_1">
        <td>Data</td>
    </tr>
</table>

<hr>

<table border="2" cellpadding="2" cellspacing="2">
    <tr>
        <th><img src="http://cdn5.iconfinder.com/data/icons/super-mono-reflection/blue/toggle-expand_blue.png" id="trigger_2"/></th>
    </tr>
    <tr id="toggle_2">
        <td>Data</td>
    </tr>
</table>
</body>
</html>

I've done some searching but I'm not sure if this is possible or not?

Any ideas or tips would be great.

Thanks

JustBaron
  • 2,229
  • 7
  • 23
  • 33

3 Answers3

0

Try this :

$(document).ready(function() {
    $('#trigger_1').click(function () { 
      $('#toggle_1', $(this).parent()).toggle();
   });
$('#trigger_2').click(function () { 
      $('#toggle_2').toggle();
   });
 });
tazorax
  • 51
  • 3
0

Instead of unneccessary id's and such, I'd approach it as

$('#trigger_2').click(function () { 
    $(this).closest('table').find('tr:not(:nth-child(1))').toggle();
});

$(this).closest('table') searches your clicked elements's parent, if it's not a table it searches this elements parents, and so on, until the parent is a table, than the find searches for every tr that is not the first child, and toggles it.

This allows for multiple lines of data that need to be toggled, without spamming id's and classes everywhere.

Stefan Candan
  • 791
  • 5
  • 10
0

I have updated with some better practices like using thead / tbody and wrapping the image in an anchor.

But do you realise if the button is inside the header then you won't be able to click it again. Is that what you meant to do or am I misunderstanding?

http://jsfiddle.net/t4b7X/

$(document).ready(function() {
    $('.table-toggle').click(function(event) { 
          $(this).closest('thead').toggle();
          event.preventDefault();
    });
});
Dominic
  • 48,717
  • 14
  • 109
  • 126