tables.modeswitch.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. * tablesaw: A set of plugins for responsive tables
  3. * Mode Switch: UI element to allow the user to change table modes: stack/swipe/columntoggle
  4. * Copyright (c) 2013 Filament Group, Inc.
  5. * MIT License
  6. */
  7. ;(function( win, $ ) {
  8. var S = {
  9. selectors: {
  10. init: 'table[data-tablesaw-mode-switch]'
  11. },
  12. attributes: {
  13. excludeMode: 'data-tablesaw-mode-exclude'
  14. },
  15. classes: {
  16. main: 'tablesaw-modeswitch',
  17. toolbar: 'tablesaw-toolbar'
  18. },
  19. modes: [ 'stack', 'swipe', 'columntoggle' ],
  20. init: function( table ) {
  21. var $table = $( table ),
  22. ignoreMode = $table.attr( S.attributes.excludeMode ),
  23. $toolbar = $table.prev().filter( '.tablesaw-bar' ),
  24. modeVal = '',
  25. $switcher = $( '<div>' ).addClass( S.classes.main + ' ' + S.classes.toolbar ).html(function() {
  26. var html = [ '<label>' + Tablesaw.i18n.columns + ':' ],
  27. dataMode = $table.attr( 'data-tablesaw-mode' ),
  28. isSelected;
  29. html.push( '<span class="btn btn-small">&#160;<select>' );
  30. for( var j=0, k = S.modes.length; j<k; j++ ) {
  31. if( ignoreMode && ignoreMode.toLowerCase() === S.modes[ j ] ) {
  32. continue;
  33. }
  34. isSelected = dataMode === S.modes[ j ];
  35. if( isSelected ) {
  36. modeVal = S.modes[ j ];
  37. }
  38. html.push( '<option' +
  39. ( isSelected ? ' selected' : '' ) +
  40. ' value="' + S.modes[ j ] + '">' + Tablesaw.i18n.modes[ j ] + '</option>' );
  41. }
  42. html.push( '</select></span></label>' );
  43. return html.join('');
  44. });
  45. var $otherToolbarItems = $toolbar.find( '.tablesaw-advance' ).eq( 0 );
  46. if( $otherToolbarItems.length ) {
  47. $switcher.insertBefore( $otherToolbarItems );
  48. } else {
  49. $switcher.appendTo( $toolbar );
  50. }
  51. $switcher.find( '.btn' ).tablesawbtn();
  52. $switcher.find( 'select' ).bind( 'change', S.onModeChange );
  53. },
  54. onModeChange: function() {
  55. var $t = $( this ),
  56. $switcher = $t.closest( '.' + S.classes.main ),
  57. $table = $t.closest( '.tablesaw-bar' ).nextUntil( $table ).eq( 0 ),
  58. val = $t.val();
  59. $switcher.remove();
  60. $table.data( 'table' ).destroy();
  61. $table.attr( 'data-tablesaw-mode', val );
  62. $table.table();
  63. }
  64. };
  65. $( win.document ).on( "tablesawcreate", function( e, Tablesaw ) {
  66. if( Tablesaw.$table.is( S.selectors.init ) ) {
  67. S.init( Tablesaw.table );
  68. }
  69. });
  70. })( this, jQuery );