// get table which needs the floating header var mainTable = document.getElementById("main-table"); var mainTableThead = mainTable.getElementsByTagName("thead")[0]; //get wrapping div var wrappingDiv = document.getElementById("wrappingDiv"); //creating floating table and grab thead var target = createFloatTable(mainTable); //get top x which will stay the same for the header var baseTop = mainTableThead.getBoundingClientRect().top; var baseLeft = mainTableThead.getBoundingClientRect().left; //on scroll wrappingDiv.addEventListener("scroll", floatThead); //create floating head table function createFloatTable(tableToCopyNode) { var floatTable = document.createElement("TABLE"); floatTable.setAttribute("id", "float-table"); //var parent = tableToCopyNode.parentNode; //insert into floating div var floating = document.getElementById("floating"); floating.appendChild(floatTable); //insert float table in parent node before actual table //parent.insertBefore(floatTable, tableToCopyNode); var thead = document.createElement("THEAD"); thead.setAttribute("id", "float-thead"); document.getElementById("float-table").appendChild(thead); //grab tableToCopyNode header row th'same var headerRow = tableToCopyNode.getElementsByTagName("tr")[0]; var clone = headerRow.cloneNode(true); thead.appendChild(clone); //return table return document.getElementById("float-table"); } function floatThead() { // Get the number of pixels scrolled var amountLeft = wrappingDiv.scrollLeft; var amountTop = wrappingDiv.scrollTop; var stickHorizontal = baseLeft - amountLeft; var stickVertical = baseTop - amountTop; document.getElementById('update').innerHTML = 'Top: ' + amountTop.toString() + ' | Left: ' + amountLeft.toString(); // Set the number of pixels scrolled target.style.marginLeft = stickHorizontal - 1 + 'px'; //target.style.marginTop = stickVertical - 1 + 'px'; }