DEV Community

Mads Stoumann
Mads Stoumann

Posted on

Populate a drop-down with function-names from external module

The use-case for this is probably very limited, but I found it useful, when I had to add a drop-down with easing-functions to a small app.

The easing-functions are in an external module called easings.mjs, and is a bunch of timing functions for animations, example:

export function linear(t) { return t; }
export function easeIn(t) { return t*t; }
export function easeOut(t) { return t*(2-t); }
etc.
Enter fullscreen mode Exit fullscreen mode

To populate a drop-down (select) with options, we need to have that element in the DOM:

<select id="easingSelect"></select>
Enter fullscreen mode Exit fullscreen mode

And, finally, the script for dynamically importing the easings.mjs file and populate the drop-down is:

/* Create a locally scoped variable for the imported module */
let easingModule;
const easingSelect = document.getElementById('easingSelect');

import('../assets/js/easing.mjs')
.then(module => {
  /* If import is succesful, assign imported module to local variable */
  easingModule = module;
  for (const func in module) {
    /*
    Iterate functions/methods in module.
    Add an option for each, assign innerText and value in one go
    */
    const option = document.createElement('option');
    option.innerText = option.value = func.toString();
    easingSelect.appendChild(option)
  }
});
/*
Add onChange-listener.
If selected value (function-name) exists in èasingModule`, run the function.
*/
easingSelect.addEventListener('change', () => {
  const easingFunc = easingModule[easingSelect.value];
  if (typeof easingFunc === 'function') {
    // easingFunc();
    console.log(`Run: easingFunc() ⇒ ${easingSelect.value}()`);
  }
})
Enter fullscreen mode Exit fullscreen mode

Now, whenever I add a new easing-method to easings.mjs, the drop-down is automatically updated.

Top comments (0)