Skip to content

Instantly share code, notes, and snippets.

@gggritso
Created March 28, 2014 20:50
Show Gist options
  • Save gggritso/9842716 to your computer and use it in GitHub Desktop.
Save gggritso/9842716 to your computer and use it in GitHub Desktop.
Snap.svg addClass and removeClass
Snap.plugin( function( Snap, Element, Paper, global ) {
Element.prototype.addClass = function( klasses ) {
if ( !( klasses instanceof Array ) ) { klasses = [ klasses ]; }
var currentKlasses = ( this.attr( 'class' ) || '' ).split( ' ' );
if ( currentKlasses === [ '' ] ) {
this.attr({ 'class': klasses.join( ' ' ) });
return this;
}
for ( var i = 0, klass; klass = klasses[ i ++ ]; ) {
if ( currentKlasses.indexOf( klass ) === -1 ) {
currentKlasses.push( klass );
}
}
this.attr({ 'class': currentKlasses.join( ' ' ) });
return this;
};
Element.prototype.removeClass = function( klasses ) {
var ind, currentKlasses;
if ( !( klasses instanceof Array ) ) { klasses = [ klasses ]; }
currentKlasses = ( this.attr( 'class' ) || '' ).split( ' ' );
if ( currentKlasses === [ '' ] ) { return this; }
for ( var i = 0, klass; klass = klasses[ i ++ ]; ) {
ind = currentKlasses.indexOf( klass );
if ( ind !== -1 ) { currentKlasses.splice( ind, 1 ); }
}
this.attr({ 'class': currentKlasses.join( ' ' ) });
return this;
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment