0

I'm trying to write a simple JavaScript code (injected to a page via a Chrome extension), that will open the option list for an HTML SELECT control (for the interactive user to see), so I thought about simulating a user click on the control. I'm able to trigger a click event on a BUTTON via JavaScript, but the SELECT control refuses my attempts.

function triggerClick(domElmId) {
    let domElm = document.getElementById(domElmId);
    triggerEvent(domElm, 'mouseover');
    triggerEvent(domElm, 'mousedown');
    triggerEvent(domElm, 'click');
    triggerEvent(domElm, 'mouseup');  
}
function triggerEvent(domElm, eventName) {
    let options = {pointerX: 0, pointerY: 0, button: 0, ctrlKey: false, altKey: false, shiftKey: false, metaKey: false, bubbles: true, cancelable: true};
    let eventType = 'MouseEvents';
    let oEvent = null;
    oEvent = new MouseEvent(eventName, options);
    domElm.dispatchEvent(oEvent);
}

code example: https://codepen.io/anon/pen/mBegaq

Any ideas?

Uri Kalish
  • 13
  • 4

1 Answers1

0

Browsers don't allow expanding <select> in javascript. Then can only be expanded by clicking with the mouse.

However, if you really need to do this. There is a solution: https://code.google.com/archive/p/expandselect/

This works by creating another <select> with multiple options all displayed at once. This is then positioned over the old control.

Alternately, take a look at this question for some ideas: Is it possible to use JS to open an HTML select to show its option list?

DNKROZ
  • 2,634
  • 4
  • 25
  • 43
  • Thanks! Do you know if this behavior is specific to a SELECT control, or are there other HTML controls like it that refuse simulated JS clicks? – Uri Kalish Sep 18 '17 at 11:18
  • Good question. I'm not too sure to be honest. `select` is the only one I've come across so far – DNKROZ Sep 18 '17 at 11:50