JSFiddle - React, Tailwind, and code Playground
HTML
<div class="table-container">
<table>
</table>
</div>
CSS
body {
font-family: sans-serif;
}
.table-container {
border: 10px solid #666;
height: 400px;
overflow: scroll;
width: 400px;
}
table {
border-collapse: collapse;
}
td {
color: #999;
padding: 5px;
}
}
JavaScript
var $container = $('.table-container');
var $table = $container.find('table');
for (var i = 0; i <= 100; i += 1) {
var $tr = $('<tr>');
for (var j = 1; j <= 100; j += 1) {
var $td = $('<td>', { text: j + i });
$td.appendTo($tr);
}
$tr.appendTo($table);
}
var previousScroll = [0, 0];
var correction = false;
// Adjust the threshold to a larger number if you'd like it
// to take longer to switch between horizontal and vertical
// scrolling
var threshold = 10;
var direction;
var directionTimeout;
$container.on('scroll', function (event) {
if (!correction) {
var element = event.currentTarget,
$element = $(event.currentTarget),
x = element.scrollLeft,
y = element.scrollTop;
var diff = [
Math.abs(x - previousScroll[0]),
Math.abs(y - previousScroll[1])
];
console.log(diff[0], diff[1]);
correction = true;
if (!direction) {
console.log('resetting direction');
if (diff[0] > diff[1]) {
direction = 'horizontal';
} else if (diff[0] < diff[1]) {
direction = 'vertical';
} else {
direction = 'vertical';
}
}
debugger;
if (direction === 'horizontal') {
console.log('horizontal scroll');
$element.scrollTop(previousScroll[1]);
previousScroll = [x, previousScroll[1]];
} else {
console.log('vertical scroll');
$element.scrollLeft(previousScroll[0]);
previousScroll = [previousScroll[0], y];
}
clearTimeout(directionTimeout);
directionTimeout = setTimeout(function () {
direction = null;
}, threshold);
} else {
correction = false;
}
});