31
loading...
This website collects cookies to deliver better user experience
In this article I will show you how to create a sticky column on table scroll.
position:sticky
. Applying this to say a div
element will make it stick to its parent element. The good news is that this will also work for Table Cells ! tr
& thead
elements ) div
element , and within this you can create a good ol' fashioned HTML table with enough columns so that we'll be required to scroll horizontally..films-container{
width:600px;
overflow:auto;
}
postion:sticky
and the location it is going to stick when scrolling starts and the element gets to. We'll also set the z-index and background-color to ensure that it appears over any of the other elements and remains visible..stick-column{
position: -webkit-sticky;
position: sticky;
left: 0;
background: #ffff !important;
z-index:9;
}
td
in the column. nth-child
selector. td
using the above and querySelectorAll
. When we have these we can add our class , but first we need to remove the class from any other column that may have it as well because it will interfere with the current one.function ClickColumn(){
var index = this.cellIndex
var selector = 'td:nth-child('+(index+1)+')'
var cells = document.querySelectorAll(selector);
// Check if trying to unclick the same column
// If not then proceed , as we want to be able to unclick the functionality
if(!cells[0].classList.contains('stick-column')){
// Get the Previous Clicked Element and remove Class
var previous = document.getElementsByClassName('stick-column');
while(previous[0]) {
previous[0].classList.remove('stick-column');
}
}
for(var i = 0 ; i < cells.length ; i++) {
if(cells[i].classList.contains('stick-column') ){
cells[i].classList.remove('stick-column');
}
else{
cells[i].classList.add('stick-column');
}
}
}
document.querySelectorAll('#film-tbl thead td')
.forEach(e => e.addEventListener("click", ClickColumn )
);