make html table scrollable in typescript

To make an HTML table scrollable in TypeScript, you can use CSS to create a fixed height container for the table, and set the overflow property to "auto" or "scroll". Here's an example of how to create a scrollable HTML table in TypeScript:

index.ts
// Define the table body data
const tableData = [
    { name: "John", age: 32, email: "john@example.com" },
    { name: "Jessica", age: 26, email: "jessica@example.com" },
    { name: "Mark", age: 48, email: "mark@example.com" },
    { name: "Samantha", age: 35, email: "samantha@example.com" },
    { name: "Charlie", age: 29, email: "charlie@example.com" },
    { name: "Alex", age: 41, email: "alex@example.com" }
];

// Create the table element
const table = document.createElement("table");

// Create the table header
const headerRow = table.insertRow();
for (const key in tableData[0]) {
    const headerCell = document.createElement("th");
    headerCell.innerHTML = key;
    headerRow.appendChild(headerCell);
}

// Create the table body
const tableBody = document.createElement("tbody");
for (const data of tableData) {
    const row = tableBody.insertRow();
    for (const key in data) {
        const cell = row.insertCell();
        cell.innerHTML = data[key];
    }
}

// Append the table body to the table element
table.appendChild(tableBody);

// Create a container for the table and set its height
const container = document.createElement("div");
container.style.height = "200px";

// Create a style element and set the overflow property to "auto"
const style = document.createElement("style");
style.innerHTML = `
    div {
        overflow: auto;
    }
`;

// Append the table and style elements to the container element
container.appendChild(style);
container.appendChild(table);

// Append the container element to the document body
document.body.appendChild(container);
1592 chars
53 lines

In this example, we create an HTML table from an array of data using TypeScript. We then create a container element with a fixed height of 200px and set its overflow property to "auto", which will create a scrollable area. We append the table to the container and append the container to the document body.

Note that you may need to adjust the height of the container to fit your specific use case, and you can also adjust the overflow property to "scroll" if you want to always show the scrollbar, even if there is no overflow.

gistlibby LogSnag