Skip to content
Advertisement

Using buttons to scroll dropdown

I would like to use ‘up’ and ‘down’ buttons to scroll through options. Ultimately, the actual dropdown list will be hidden from the user. This example I have left it visible. I can’t use onclick in the button tag because this will be a Chrome Extension. The issue is the buttons don’t seem to do anything.

document.addEventListener('DOMContentLoaded', function() {  
    document.getElementById('d').addEventListener('click', theme(this));
    document.getElementById('u').addEventListener('click', theme(this));
});
var ddl = document.getElementById("s")
function theme(x) {
  if (x.value === 'down') {
    ddl.selectedIndex = ddl.selectedIndex + 1
  } else {
    ddl.selectedIndex = ddl.selectedIndex - 1
  }
};
<select id="s">
    <option>Dog</option>
    <option>Cat</option>
    <option>Bird</option>
    <option>Lizard</option>
    <option>Snake</option>   
</select>
    <button id="d" type="button" value="up">up</button>
    <button id="u" type="button" value="down">down</button>
    <script src="test.js"></script>

Advertisement

Answer

There are 2 problems with this bit addEventListener('click', theme(this));. You think it will call theme(this) when you click the button and this will be the button you clicked on. But first, this in this context is window not the button and second, theme(this) is called immediately when addEventListener is executed, and as it doesn’t return anything you don’t attach any event listeners. Try this instead:

document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('d').addEventListener('click', () => theme('up'));
    document.getElementById('u').addEventListener('click',() => theme('down'));
});
var ddl = document.getElementById("s")
function theme(x) {
  if (x === 'down') {
    ddl.selectedIndex = ddl.selectedIndex + 1
  } else if(ddl.selectedIndex > 0){
      ddl.selectedIndex = ddl.selectedIndex - 1
  }
};
<select id="s">
    <option>Dog</option>
    <option>Cat</option>
    <option>Bird</option>
    <option>Lizard</option>
    <option>Snake</option>   
</select>
    <button id="d" type="button" value="up">up</button>
    <button id="u" type="button" value="down">down</button>
    <script src="test.js"></script>
Advertisement