We’ve written a bit about the Priority+ pattern here before. Here’s a bunch of real world examples. I needed to use it recently. I found Gijs Rogé’s priority-navigation . It’s pretty nice: no dependencies, clean code, fairly configurable and designable. It’s not particularly small though, and there is a good amount of it defining helper functions. I was in an environment that had all that stuff available and so I figured I’d take a crack at a version.
Technique: Test if Elements Have Wrapped
This version has jQuery (for DOM easiness) and Lodash (for debouncing) as dependencies. Those are far from insignificant, and you wouldn’t probably add them just for navigation, but my project had them available.
I also took a slightly different approach than I’ve seen in other takes. Rather than measure the available width and the width of each menu item to see if they will fit or not, I just let the menu items wrap. When the window is resized, I check the position of the elements and if I can tell by their position that they have wrapped, they go into the overflow. So you never really see any wrapping. (If your menu items can wrap, you probably don’t need Priority+.)
Of course there is work to be done. With the information about which items should be in the overflow, I needed to clone them over there. And be ready to do it all over again when the window resizes, but not too quickly (hence the debouncing ).
Technique: Measure Widths
The technique I see more commonly is to measure widths and make choices based on those widths. Johan van Tongeren has a version of that:
The code is quite short. Measure the available space and space needed by the elements. If there isn’t enough space, pluck one off into the overflow and try again. It seems like a lot of calculation, especially the recursion and that it’s not debounced, but hey it seems to run pretty ok.
Luke Jacksonn has written a version in a simliar fashion:
Technique: Choose Overflow Items Ahead of Time
It uses the
to hide/show a set of links. He uses alpha/beta/gamma classes on the links in conjunction with media queries to show more/less of them at different screen widths.
Uhm. I guess it’s that you can always snag someone else’s code to get something done. Very often that’s a good idea. But sometimes it’s fun to dig in a little and try to write it yourself and explore other possibilities. I’m not sure my version is any better (it’s not), but I learned about the problem and different possible approaches.