Skip to content

Commit

Permalink
adding force parameter for toggle(), along with tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Dominic Barnes committed Sep 25, 2013
1 parent 7318f48 commit 0e55184
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 7 deletions.
31 changes: 25 additions & 6 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -112,26 +112,45 @@ ClassList.prototype.removeMatching = function(re){
};

/**
* Toggle class `name`.
* Toggle class `name`, can force state via `force`.
*
* For browsers that support classList, but do not support `force` yet,
* the mistake will be detected and corrected.
*
* @param {String} name
* @param {Boolean} force
* @return {ClassList}
* @api public
*/

ClassList.prototype.toggle = function(name){
ClassList.prototype.toggle = function(name, force){
// classList
if (this.list) {
this.list.toggle(name);
if ("undefined" !== typeof force) {
if (force !== this.list.toggle(name, force)) {
this.list.toggle(name); // toggle again to correct
}
} else {
this.list.toggle(name);
}
return this;
}

// fallback
if (this.has(name)) {
this.remove(name);
if ("undefined" !== typeof force) {
if (!force) {
this.remove(name);
} else {
this.add(name);
}
} else {
this.add(name);
if (this.has(name)) {
this.remove(name);
} else {
this.add(name);
}
}

return this;
};

Expand Down
30 changes: 29 additions & 1 deletion test/classes.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ describe('classes(el)', function(){
})
})

describe('.toggle(class)', function(){
describe('.toggle(class, force)', function(){
describe('when present', function(){
it('should remove the class', function(){
el.className = 'foo bar hidden';
Expand All @@ -67,6 +67,34 @@ describe('classes(el)', function(){
assert('foo bar hidden' == el.className);
})
})

describe('when force is true', function(){
it('should add the class', function(){
el.className = 'foo bar';
classes(el).toggle('hidden', true);
assert('foo bar hidden' == el.className);
})

it('should not remove the class', function(){
el.className = 'foo bar hidden';
classes(el).toggle('hidden', true);
assert('foo bar hidden' == el.className);
})
})

describe('when force is false', function(){
it('should remove the class', function(){
el.className = 'foo bar hidden';
classes(el).toggle('hidden', false);
assert('foo bar' == el.className);
})

it('should not add the class', function(){
el.className = 'foo bar';
classes(el).toggle('hidden', false);
assert('foo bar' == el.className);
})
})
})

describe('.array()', function(){
Expand Down

0 comments on commit 0e55184

Please sign in to comment.