I figured out what I needed to do; without a guard to skip the whole operation on lower-level submenus I’d end up in a deadly cycle. The solution was to add this as the first line of the event handler:
if ($(menu).parentsUntil('#main-menu').length != 1) return;
Now it works just fine.