Advertisement
Quiver

classie.js

Aug 17th, 2015
415
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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.  
  11. /*jshint browser: true, strict: true, undef: true */
  12. /*global define: false */
  13.  
  14. ( function( window ) {
  15.  
  16. 'use strict';
  17.  
  18. // class helper functions from bonzo https://github.com/ded/bonzo
  19.  
  20. function classReg( className ) {
  21.   return new RegExp("(^|\\s+)" + className + "(\\s+|$)");
  22. }
  23.  
  24. // classList support for class management
  25. // altho to be fair, the api sucks because it won't accept multiple classes at once
  26. var hasClass, addClass, removeClass;
  27.  
  28. if ( 'classList' in document.documentElement ) {
  29.   hasClass = function( elem, c ) {
  30.     return elem.classList.contains( c );
  31.   };
  32.   addClass = function( elem, c ) {
  33.     elem.classList.add( c );
  34.   };
  35.   removeClass = function( elem, c ) {
  36.     elem.classList.remove( c );
  37.   };
  38. }
  39. else {
  40.   hasClass = function( elem, c ) {
  41.     return classReg( c ).test( elem.className );
  42.   };
  43.   addClass = function( elem, c ) {
  44.     if ( !hasClass( elem, c ) ) {
  45.       elem.className = elem.className + ' ' + c;
  46.     }
  47.   };
  48.   removeClass = function( elem, c ) {
  49.     elem.className = elem.className.replace( classReg( c ), ' ' );
  50.   };
  51. }
  52.  
  53. function toggleClass( elem, c ) {
  54.   var fn = hasClass( elem, c ) ? removeClass : addClass;
  55.   fn( elem, c );
  56. }
  57.  
  58. var classie = {
  59.   // full names
  60.   hasClass: hasClass,
  61.   addClass: addClass,
  62.   removeClass: removeClass,
  63.   toggleClass: toggleClass,
  64.   // short names
  65.   has: hasClass,
  66.   add: addClass,
  67.   remove: removeClass,
  68.   toggle: toggleClass
  69. };
  70.  
  71. // transport
  72. if ( typeof define === 'function' && define.amd ) {
  73.   // AMD
  74.   define( classie );
  75. } else {
  76.   // browser global
  77.   window.classie = classie;
  78. }
  79.  
  80. })( window );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement