classie.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*!
  2. * classie - class helper functions
  3. * from bonzo https://github.com/ded/bonzo
  4. *
  5. * classie.has( elem, 'my-class' ) -> true/false
  6. * classie.add( elem, 'my-new-class' )
  7. * classie.remove( elem, 'my-unwanted-class' )
  8. * classie.toggle( elem, 'my-class' )
  9. */
  10. /*jshint browser: true, strict: true, undef: true */
  11. /*global define: false */
  12. ( function( window ) {
  13. 'use strict';
  14. // class helper functions from bonzo https://github.com/ded/bonzo
  15. function classReg( className ) {
  16. return new RegExp("(^|\\s+)" + className + "(\\s+|$)");
  17. }
  18. // classList support for class management
  19. // altho to be fair, the api sucks because it won't accept multiple classes at once
  20. var hasClass, addClass, removeClass;
  21. if ( 'classList' in document.documentElement ) {
  22. hasClass = function( elem, c ) {
  23. return elem.classList.contains( c );
  24. };
  25. addClass = function( elem, c ) {
  26. elem.classList.add( c );
  27. };
  28. removeClass = function( elem, c ) {
  29. elem.classList.remove( c );
  30. };
  31. }
  32. else {
  33. hasClass = function( elem, c ) {
  34. return classReg( c ).test( elem.className );
  35. };
  36. addClass = function( elem, c ) {
  37. if ( !hasClass( elem, c ) ) {
  38. elem.className = elem.className + ' ' + c;
  39. }
  40. };
  41. removeClass = function( elem, c ) {
  42. elem.className = elem.className.replace( classReg( c ), ' ' );
  43. };
  44. }
  45. function toggleClass( elem, c ) {
  46. var fn = hasClass( elem, c ) ? removeClass : addClass;
  47. fn( elem, c );
  48. }
  49. var classie = {
  50. // full names
  51. hasClass: hasClass,
  52. addClass: addClass,
  53. removeClass: removeClass,
  54. toggleClass: toggleClass,
  55. // short names
  56. has: hasClass,
  57. add: addClass,
  58. remove: removeClass,
  59. toggle: toggleClass
  60. };
  61. // transport
  62. if ( typeof define === 'function' && define.amd ) {
  63. // AMD
  64. define( classie );
  65. } else {
  66. // browser global
  67. window.classie = classie;
  68. }
  69. })( window );