dropdown menu without viewof

I’m teaching d3 using Observable, and want to show how to create dropdown menus. Because I want students to be able to use the code they are learning outside of Observable, I would prefer not to use Observable-specific functionality like viewOf. I’m having trouble getting select working with buttons for the equivalent of an html dropdown menu. I’d appreciate an example.

1 Like

I’m sure there are lots of good examples across Observable; here’s a parametric region plotter that I made recently that has an “Examples” : drop down selector:

The general pattern is pretty much how you’d build a div with bells and whistles on any webpge:

let div = d3.create('div');
let selector = div.append('select');
selector
  .append('option')
  .attr('value', 'opt')
  .text('An option')
  .property('selected', true);
selector.on('change', function() {
 'do something!'
})

Thank you so much!
There is one error in your code above: the first line should be
let div = d3.create(‘div’)
which I got from the linked code.

1 Like

BTW I’m having trouble finding the “create” function in the d3 API, and I don’t recall seeing it before this.

It’s part of d3-selection:

I think it’s less common when building webpages because you can typically select something that’s already in the webpage and go from there. I’ve found it handy in some situations even there, though.

Thanks so much! I’ve never noticed this part of the selection API. Having a detached element in the current document is exactly what is needed. This was so helpful!

1 Like