Created
December 9, 2017 11:04
-
-
Save libkazz/9f10e9697b259e9d61663f258b29483b to your computer and use it in GitHub Desktop.
colspan = 2 のカラムの toggle する
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
console.log('Loaded..'); | |
class Togglable { | |
constructor(th) { | |
this.th = th; | |
this.table = th.parentNode.parentNode.parentNode; | |
this.tds = this.table.querySelectorAll('td:nth-child(' + this._getColumnIndex(th) + ')') | |
} | |
toggle() { | |
if(this.th.getAttribute('data-toggle') === 'hide') { | |
this.showColumn(); | |
} else { | |
this.hideColumn(); | |
} | |
} | |
showColumn() { | |
this.th.setAttribute('data-toggle', 'show'); | |
this.th.setAttribute('colspan', 2); | |
this.tds.forEach(function(td){ td.setAttribute('style', null); }); | |
} | |
hideColumn() { | |
this.th.setAttribute('data-toggle', 'hide'); | |
this.th.setAttribute('colspan', 1); | |
this.tds.forEach(function(td){ td.setAttribute('style', 'display:none'); }); | |
} | |
_getColumnIndex(th) { | |
let ths = th.parentNode.querySelectorAll('th'); | |
let index = 1; | |
for(let i = 0; i < ths.length; i++) { | |
// Get left column of this "th" | |
if(ths[i] === th) return index++; | |
let delta_index = 0 | |
if(ths[i].getAttribute('data-toggle') === 'hide') { | |
// NOTE: Doesn't care about case of `colspan > 2`. | |
delta_index = 2 | |
} else { | |
delta_index = parseInt(ths[i].getAttribute('colspan') || 1) | |
} | |
index += delta_index; | |
}; | |
} | |
} | |
[].forEach.call(document.querySelectorAll('th[colspan]'), function(th) { | |
th.addEventListener('click', function(e) { | |
togglable = new Togglable(e.target); | |
togglable.toggle(); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment