I am currently implementing a responsive design feature on my website, where I need to hide certain columns of a table when the viewport size decreases beyond a specific point. Initially, I tried using .style.visibility = "collapse"
for all <tr>
elements and .style.opacity = "0"
for all <td>
elements. Additionally, I had to manipulate the table's background
to ensure that the width of the table expands by 160% so that the remaining columns fill the screen.
While this method works fine on Chrome, Firefox, IE (including ie8!), and mobile browsers, it feels like a bit of a workaround. Are there any other more efficient solutions for achieving this?
var jmq = window.matchMedia("screen and (max-width: 610px)");
jmq.addListener(jmqListener);
function jmqListener(jmq){
var colTitle = getElementsByClassName('col-title');
var colName = getElementsByClassName('col-name');
var colDate = getElementsByClassName('col-date');
var colFb = getElementsByClassName('col-fb');
var table = getElementsByClassName('default');
if (jmq.matches || window.innerWidth < 611 ) {
//Mobile view
... resize controls
// hide specified table columns
if (colName !== null){
for(var i=0,j=colName.length; i<j; i++){
colName[i].style.visibility = "collapse";
colName[i].style.opacity = "0";
}
}
// Workaround - increase table width and hide background to prevent showing reserved space
if (table !== null){
for(var i=0,j=table.length; i<j; i++){
table[i].style.width = "160%";
table[i].style.background = "transparent";
}
}
} else {
// Desktop view
... restore control layout for desktop
// show hidden table column(s)
if (colName !== null){
for(var i=0,j=colName.length; i<j; i++){
colName[i].style.visibility = "visible";
colName[i].style.opacity = "100";
}
}
if (table !== null){
for(var i=0,j=table.length; i<j; i++){
table[i].style.width = "100%";
table[i].style.background = "#C8C8C8";
}
}
}
}
function getElementsByClassName(className) {
if (document.getElementsByClassName) {
return document.getElementsByClassName(className);
} else {
return document.querySelectorAll('.' + className);
}
}