So, I decided to start really learning CSS more in-depth, and I began by attempting to implement a pure-CSS drop-down menu/select-box. I started by studying the code available in some online tutorials.
Ultimately, I came up with this, which I think is pretty decent. However, I’ve come to the conclusion that CSS menus might never be a suitable replacement for Javascript menus in all cases, because there are subtle problems that come up when you ditch Javascript.
If the items in your drop-down menu are simply <a href links, everything should be fine. BUT if you want each link to fire a Javascript event, you run into the following issues:
-
When the user clicks an item in the drop-down box, you want the
drop-down box to disappear, obviously. This happens automatically
if the items in your drop-down box are<a>elements. If they’re
NOT<a>elements, the drop-down box won’t disappear on-click –
which leaves you with two options: (A) wire up some Javascript that
listens foronclickand then make the drop-down box disappear, or
(B) use the css:activeselector to set the drop-down box’s
displayproperty tonone. (A) is stupid, because you’re
basically back to Javascript menus at that point, and (B) doesn’t
work out because it prevents Javascript events from firing when you
click an item in the menu. -
So, you have to use
<a>tags. That means if you want to
associate an event with a menu-item selection, you need to use an
inlineonclickin your<a>tag. That’s fine, except if you do
that, it prevents the drop-down menu from disappearing (as
demonstrated in my jsfiddle link). So, really, CSS-only
drop-down menus only seem to be workable if all you want to do when
the user selects a menu item is navigate to another page via an<a>
link. I can’t find any way to get a Javascript function to fire that
doesn’t come with some gotcha.
Question: So, is what I’ve said accurate? Or is there a way to create a CSS-only drop-down menu that (A) disappears when the user clicks it, and (B) triggers a Javascript function?
I think that you’re a bit confused. You seem to think that there is a binary that exists: either all CSS or all JS. This is a silly way to think. You should use CSS when it makes sense to use CSS and use JS to do things that CSS wasn’t made for. In most cases, using CSS to do the heavy lifting for you (hide/showing of menus, etc) and then enhancing said menu with additional functionality that CSS can’t provide is the way that most professional front end devs build menus.