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:
My knowledge of javascript is pretty amateur so I may be missing obvious things here. Any help would be appreciated.