Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop multiple select from scrolling to top when selection changes

I have a multi select list that i use to filter a grid with. When i select or deselect any item in the list, it triggers an event.

The problem is that when i scroll down and select or deselect a value lower on the list, it jumps back to the top. How can i stop this from happening?

I've made a fiddle: https://jsfiddle.net/Berge90/a2two97o/

Edit: Problems in Chrome. Works fine in Edge and Firefox

HTML

<div class="FilterContainer">
    <select id="SelectTenant" multiple="true">
    </select><br/>
    <button onclick="setAllTenantSelections(true)">Select All</button>
    <button onclick="setAllTenantSelections(false)">Select None</button>
</div>

Javascript

window.onload = setupFilter;
window.onload = populateTenantFilter;
gridHeaders = [{name: "Test"},{name: "Value"},{name: "Another one"},{name: "And another"},{name: "Last one"}];

//Selecting/Deselecting all values
function setAllTenantSelections(selected) {
    var select = document.getElementById("SelectTenant");
    for (element in select.children) {
        select[element].selected = selected;
        showCol(select[element].text, selected);
    }
}

//Adding all values from array to list
function populateTenantFilter() {
    var select = document.getElementById("SelectTenant");
    select.innerHTML = "";
    for (i = 0; i < gridHeaders.length; i++) {
        var option = document.createElement("Option");
        option.innerHTML = gridHeaders[i].name;
        select.appendChild(option);
    }
    //setting all options as selected on load
    setAllTenantSelections(true);
    setupFilter();
}

//Adding onclick-events to the values
function setupFilter() {
    $('select option').on('mousedown', function (e) {
        this.selected = !this.selected;
        if (this.selected) {
            console.log("SELECTED: " + this.text);
            showCol(this.text,true);
        } else {
            console.log("DESELECTED: " + this.text);
            showCol(this.text,false);
        }
        e.preventDefault();
    });
}

function showCol(){
        //Filtering grid based on selection
}
like image 393
Kristoffer Berge Avatar asked Apr 12 '16 13:04

Kristoffer Berge


1 Answers

I solved this by scrolling back to the original scrollTop in the next event loop:

$('.your-selector').mousedown(e => {
    var el = e.target;
    e.preventDefault();

    // ...your code

    // fixes erratic scroll behaviour in Chrome
    var scrollTop = el.parentNode.scrollTop;
    setTimeout(() => el.parentNode.scrollTo(0, scrollTop), 0);
});
like image 130
Brendan Maclean Avatar answered Sep 29 '22 19:09

Brendan Maclean