Check If an Element can be Scrolled Horizontally with JavaScript

12/22/2021
Contents
In this article, I will introduce how to check if an element can be scrolled horizontally with JavaScript.
Introduction
Follow the steps below to determine if the element can be scrolled horizontally.
- Get the width of the specified element
- Get the width of the child element of the specified element
- Compares the width of the specified element with the width of the child element
- If the width value of the child element is large, it is judged that the element can be scrolled horizontally
Code
HTML
<div class="target">
<table>
<tbody>
<tr>
<th>...</th>
<td>...</td>
</tr>
</tbody>
</table>
</div>
CSS
.target {
width: 500px;
margin: 0 auto;
overflow-y: auto;
}
table {
display: table;
width: 1280px;
border-collapse: collapse;
}
table th,
table td {
padding: 10px 20px;
border: 1px solid #384878;
}
JavaScript
//Get an Element
const target = document.querySelector('.target');
//Get the first child element that appears in the target element
const targetChild = target.children[0];
//Compares the width of the specified element with the width of the child element
if(target.clientWidth < targetChild.clientWidth){
console.log('The element can be scrolled horizontally');
} else {
console.log('The element can't be scrolled horizontally');
}