'javascript Dynamically remove/add table head columns (as array) on window resize

Initially we have:

-an array which stores all the table columns names

let theadShownColumns=[col1,col2...colX]

-an Empty array to be used

let theadHiddenColumns=[]

the theadShownColumns array items are rendered in table thead html:

<table class="q-table__middle">
<thead>
<tr>
<th> col1 </th>
<th> col2 </th>
.
.
.
<th> coX </th>
</tr>
</thead>
</table>

Aim: On window resize check

  • case 1: if screen size gets narrower , check if the thead overflows if yes remove one array item from theadShownColumns array and push the removed array item to theadHiddenColumns ( untill no overflow occurs)

-case 2: if screen size gets wider, check if theadHiddenColumns is not empty and push back array items totheadShownColumns (while no overflow occurs)

My implementation:

    async isOverflownX() {
      let element = document.getElementById('tasks-table')?.querySelector('.q-table__middle')

      if (element?.scrollWidth > element?.clientWidth) {
        await this.theadShownColumns?.length > 0 ?   this.theadHiddenColumns?.unshift(this.theadShownColumns[this.theadShownColumns.length - 1]) : ''
        await this.theadShownColumns?.length > 0 ? this.theadShownColumns.pop() : ''
        await this.isOverflownX(element)

       } else if ((element?.scrollWidth <= element?.clientWidth) && this.theadHiddenColumns?.length > 0) {
      
        await this.theadShownColumns?.push(this.theadHiddenColumns[this.theadHiddenColumns?.length-1])
        await this.theadHiddenColumns.shift()
         while (element?.scrollWidth > element?.clientWidth) {
          await this.theadShownColumns?.length > 0 ? this.theadShownColumns.pop() : ''
          await this.theadShownColumns?.length > 0 ? this.theadHiddenColumns?.unshift(this.columns[this.theadShownColumns.length - 1]) : ''
     await this.isOverflownX(element)
       }
        setTimeout(() => { this.isOverflownX(element)}, 0)
         return
     } else {
        return
      }
    },

This code is doing the job but some times on window resizing it enters an infinite loop, anyone have suggestions how this can be improved



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source