40 lines · 1.1 KB
Raw Download
1
// Function to check table width and apply class
2
function checkTableWidth(tableSelector) {
3
	const tables = document.querySelectorAll(tableSelector);
4
	const viewportWidth = window.innerWidth;
5
	
6
	if (tables.length) {
7
		tables.forEach((wrapper) => {
8
			const table = wrapper.querySelector('table');
9
			const tableWidth = table.offsetWidth;
10
			const containerWidth = wrapper.parentElement.offsetWidth;
11
			
12
			if (tableWidth > containerWidth) {
13
				if (tableWidth <= viewportWidth * 0.95) {  // Using 95% of viewport as threshold
14
					wrapper.classList.add('wide-table');
15
					wrapper.classList.remove('mobile-table');
16
				} else {
17
					wrapper.classList.add('mobile-table');
18
					wrapper.classList.remove('wide-table');
19
				}
20
			} else {
21
				wrapper.classList.remove('wide-table');
22
				wrapper.classList.remove('mobile-table');
23
			}
24
		});
25
	}
26
}
27
28
// Run on page load
29
document.addEventListener('DOMContentLoaded', () => {
30
	checkTableWidth('.table-wrapper');
31
});
32
33
// Run on window resize with debounce
34
let resizeTimer;
35
window.addEventListener('resize', () => {
36
	clearTimeout(resizeTimer);
37
	resizeTimer = setTimeout(() => {
38
		checkTableWidth('.table-wrapper');
39
	}, 50);
40
});