stucklen stucklen - 4 months ago 8
HTML Question

Make link bold if column is visible (not hidden)

I have a filter menu which I put inside a table, and when one of the links are clicked, the according column in another separate table becomes hidden, until the link is click on again.

<!-- Table for filter menu -->
<table>
<tr>
<td>
<a class="toggle-vis" data-column="1">hideColumn1</a> |
<a class="toggle-vis" data-column="2">hideColumn2</a> |
<a class="toggle-vis" data-column="3">hideColumn3</a>
</td>
</tr>
<table>

<script>
$('a.toggle-vis').on( 'click', function (e) {
e.preventDefault();
// Get the column API object
var column = table.column( $(this).attr('data-column') );
column.visible( ! column.visible() );
} );=
</script>


My aim is to have some way of showing which columns are hidden/shown, so onClick, I would like the link text to become bold or change color or whatever.
Do I need to loop through my table? I have no idea - very new to HTML so any help is appreciated and the getElementById doesn't seem to be working for me.

Answer

You can use this in order to get the clicked element, and then modify its inline-styling based on that (or use a class).

Inline styling

<!-- Table for filter menu -->
<table>
  <tr>
    <td>
      <a class="toggle-vis" data-column="1">hideColumn1</a> |
      <a class="toggle-vis" data-column="2">hideColumn2</a> |
      <a class="toggle-vis" data-column="3">hideColumn3</a>
    </td>
  </tr>
<table>

<script>
  $('a.toggle-vis').on( 'click', function (e) {
    e.preventDefault();
    // ADDED CODE
    var element = $(this);
    if (element.css('font-weight') === 'bold') {
      element.css({
        'font-weight': 'normal'
      });
    } else {
      element.css({
        'font-weight': 'bold'
      });
    }
    // END OF ADDED CODE
    // Get the column API object
    var column = table.column( $(this).attr('data-column') );
    column.visible( ! column.visible() );
  } );=
</script>

Classes

With classes, this is even simpler. Add this to your style: .bold-link { font-weight: bold; }

and then, just use this function:

<script>
  $('a.toggle-vis').on( 'click', function (e) {
    e.preventDefault();
    // ADDED CODE
    var element = $(this);
    element.toggleClass('bold-link');
    // END OF ADDED CODE
    // Get the column API object
    var column = table.column( $(this).attr('data-column') );
    column.visible( ! column.visible() );
  } );=
</script>