0

This question already has an answer here:

i want to fix first column (ex: Title column) of my sharepoint list view, so that whenever the user scroll horizontally the first column should be fixed. enter image description here

Thanks in advance for your support.

marked as duplicate by Ganesh Sanap, MHeld, Aakash Maurya, Gaurravs, Mohamed El-Qassas MVP Apr 16 at 10:55

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    No.. in this post user suggest a work around, but i am looking for a piece of code to achieve the above requirement. Thanks! – Mayank Surana Apr 15 at 10:36
0

You could use position CSS property with sticky value (doesn't work with IE). You would iterate over the table HTML rows to update row style.

However, since it's a table, you need to know which cell refers to the field to freeze. To do so, we will retrieve all our fields index (cells position):

var tableFieldsIndex = new Object; // Contains [fieldName] = index
var viewFields = ctx.ListSchema.Field; // All fields
viewFields.forEach(function(field, index) {
    tableFieldsIndex[field.Name] = parseInt(index);
});

Now let us iterate over all the rows being displayed and freeze every second cell:

var tableRows = document.getElementsByClassName('ms-listviewtable')[0].rows;
[].forEach.call(tableRows, function(tr) {
    var cells = tr.getElementsByClassName('ms-cellstyle');
    cells[1].style.position = 'sticky'; // Freezing cell 2
    cells[1].style.left = (5+(i*90)) +'px';
});

What may be even more interesting now is to define some function that would freeze specified fields.

function freezeColumns(fields) { // An array of fields name (strings)
    if(!fields || !ctx)
        return false;

    // Fields index (cells)
    var tableFieldsIndex = new Object;
    var viewFields = ctx.ListSchema.Field;
    viewFields.forEach(function(field, index) {
        tableFieldsIndex[field.Name] = parseInt(index);
    });

    // Iterate over displayed rows
    var table = document.getElementsByClassName('ms-listviewtable');
    var tableRows = table && table[0].rows ? (ctx.inGridMode ? table[1].rows : table[0].rows) : []; // Deal with edit mode
    [].forEach.call(tableRows, function(tr) {
        var cells = tr.getElementsByClassName('ms-cellstyle');
        for(var i=0;i<fields.length;i++) {
            var cellIndex = tableFieldsIndex[fields[i]];
            if(cells[cellIndex]) { // Be sure given field is actually displayed
                cells[cellIndex].style.position = 'sticky';
                cells[cellIndex].style.left = (5+(i*90)) +'px'; // Add an offset to make sure sticky fields won't overlap
                cells[cellIndex].style.backgroundColor = ctx.inGridMode ? 'white' : 'inherit';
            }
        }
    });

}

Not the answer you're looking for? Browse other questions tagged or ask your own question.