1

I'm attempting to code my site so that users can select multiple options without the need to hold ctrl. I have a current solution that lets me select multiple options, but it seems that whenever I select an option in my window below the default dimensions of the box, the scroll jumps back up to the top.

I had found this solution but a lot of the more reliable answers seem to be in JQuery, but I'd like to stick to vanilla JS. The pure JS solution offered lower on the page gives me an error about the element part being undefined, why is that?

element.onmousedown= function(event) {
    //this == event.target
    event.preventDefault();
    var scroll_offset= this.parentElement.scrollTop;
    this.selected= !this.selected;
    this.parentElement.scrollTop= scroll_offset;
}
element.onmousemove= function(event) {
    event.preventDefault();
}

This is the code I'm currently using,

window.onmousedown = function (e) {
    var el = e.target;
    if (el.tagName.toLowerCase() == 'option' && el.parentNode.hasAttribute('multiple')) {
        e.preventDefault();

        // toggle selection
        if (el.hasAttribute('selected')) el.removeAttribute('selected');
        else el.setAttribute('selected', '');
    }
}

I've also seen some comments around regarding ScrollTop, but anytime I've tried to implement it I've gotten errors saying it's not defined.

Here are a couple jsfiddles that emulate what I'm aiming for, but in JQuery:

Example 1

Example 2

My knowledge of javascript is pretty amateur so I may be missing obvious things here. Any help would be appreciated.

Mance Rah
  • 111
  • 9

1 Answers1

0

pure vanilla JS example.

you should do like below.

var options = document.querySelectorAll('#WOStatusKey option');
for (const item of options) {
item.addEventListener("mousedown", function(e) {
    e.preventDefault();
    var originalScrollTop = this.parentElement.scrollTop;
    this.selected = this.selected ? false : true;
    var self = this;
    this.parentElement.focus();
    setTimeout(function() {
        self.parentElement.scrollTop = originalScrollTop;
    }, 0);
    
    return false;
});
}
    <select multiple id="WOStatusKey" name="WOStatusKey" style="width:200px;">                
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="6">6</option>
        <option value="7">7</option>
        <option value="8">8</option>
        <option value="9">9</option>
        <option value="10">10</option>
        <option value="11">11</option>
    </select>

I think there is no need explanation for code. this is simple

Nbody
  • 1,168
  • 7
  • 33