Making the top row and left column “sticky” in a table automatically created with javascript

I have a simple javascript test (in a stand alone html page) to generate and display a table of any given size. I have used it to understand how the table formats. For example, if I want a 10*10 table, I press “try it” and enter 10 and the table will be generated in the javascript function with vertical and horizontal scroll bars.

I want to automatically make the top row and left hand column “sticky”. There is plenty of information available on how to do this with html and css. However, I need the javascipt to automatically make them sticky.

<!DOCTYPE html>

<html>

<head>

</head>

<body>

<style>

table, td {

border: 1px solid black;

}

.layer0stylenormal

{

text-decoration: none;

background-color: #FFF0F5;

border: 4px solid #C71585;

border-radius: 10px;

}

@media print {

table {

width: 100%

}

}

</style>

<p>Click the button .</p>

<div id="layer1">

<table id="table">

</table>

</div>

<br>

<button type="button" onclick="myFunction()">Try it</button>

<button type="button" onclick="myPrintFunction()">print it</button>

<script>

var table = document.getElementById("table");

var layer1 = document.getElementById("layer1");

function myFunction() {

layer1.className="layer0stylenormal";

layer1.style.position = 'absolute';

layer1.style.zIndex = "1000";

layer1.style.height ="400px";

layer1.style.width = "600px";

layer1.style.maxWidth = "600px";

layer1.style.top="200px";

layer1.style.left="100px";

table.style.height ="390px";

table.style.width = "590px";

table.style.overflow="auto";

layer1.style.overflow="auto";

var numberofrc = prompt("Please enter number", "");

for(var r=0;r<numberofrc;r++)

{

var x=table.insertRow(r);

for(var c=0;c<numberofrc;c++)

{

var y= x.insertCell(c);

table.rows[r].cells[c].innerHTML = "xxxx yyyyyyy" + String(r*c);

}

}

if (confirm('Do you want to print this list?')) {

newWin= window.open("");

newWin.document.write(table.outerHTML);

newWin.print();

newWin.close();

}

}

function myPrintFunction(){

newWin= window.open("");

newWin.document.write(table.outerHTML);

newWin.print();

newWin.close();

}

</script>

</body>

</html>

JS doesn’t make them sticky, CSS makes them sticky. You can use JS to set the necessary CSS properties to make them sticky. It seems like you already know how to do this since you are doing it with #layer1 and the table. So if you know how to do sticky columns with CSS then just set those CSS properties using JS like you are doing for the other elements.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.