classie.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. ( function( window ) {
  12. 'use strict';
  13. // class helper functions from bonzo https://github.com/ded/bonzo
  14. function classReg( className ) {
  15. return new RegExp("(^|\\s+)" + className + "(\\s+|$)");
  16. }
  17. // classList support for class management
  18. // altho to be fair, the api sucks because it won't accept multiple classes at once
  19. var hasClass, addClass, removeClass;
  20. if ( 'classList' in document.documentElement ) {
  21. hasClass = function( elem, c ) {
  22. return elem.classList.contains( c );
  23. };
  24. addClass = function( elem, c ) {
  25. elem.classList.add( c );
  26. };
  27. removeClass = function( elem, c ) {
  28. elem.classList.remove( c );
  29. };
  30. }
  31. else {
  32. hasClass = function( elem, c ) {
  33. return classReg( c ).test( elem.className );
  34. };
  35. addClass = function( elem, c ) {
  36. if ( !hasClass( elem, c ) ) {
  37. elem.className = elem.className + ' ' + c;
  38. }
  39. };
  40. removeClass = function( elem, c ) {
  41. elem.className = elem.className.replace( classReg( c ), ' ' );
  42. };
  43. }
  44. function toggleClass( elem, c ) {
  45. var fn = hasClass( elem, c ) ? removeClass : addClass;
  46. fn( elem, c );
  47. }
  48. window.classie = {
  49. // full names
  50. hasClass: hasClass,
  51. addClass: addClass,
  52. removeClass: removeClass,
  53. toggleClass: toggleClass,
  54. // short names
  55. has: hasClass,
  56. add: addClass,
  57. remove: removeClass,
  58. toggle: toggleClass
  59. };
  60. })( window );