Rectangle 27 0

JavaScript Rendering with a Live Filter

There are several ways you can go about this. Here are just three.

How about having a filter? I just wrote one the other day. Add a text field to the dropdown. As the user types, filter the dropdown items. Set a fixed height on the dropdown so that you can limit its height and allow vertical scrolling in the event of many dozens of items.

  • Hundreds of items in a dropdown is bad UX design.
  • Memory. Loading 500 AR objects into memory to display the dropdown isn't always a good idea. Although you can use caching to mitigate this.
  • Template compile time. Again, rendering 500 partials, or 500 fragments may not be ideal. Again, you can use fragment caching to mitigate this.
  • Performance on mobile devices. If the user is using a mobile device, this could slow things down considerably.

This is nearly the same as the above, but instead of loading all items before hand, you show a small subset of results, maybe the most popular. But when the user types a search query, instead of filtering on the client side, make an ajax request and fetch results that match the search query. This adds some complexity, but it solves most of the problems outlined in the first approach.

Almost the same as option one, but instead of rendering the dropdown on the server, return JSON to the client, and use a JS framework, like ReactJS, or plain Javascript to build the dropdown after the page is loaded.

As you can see, there are many ways to solve this. You have to choose the right approach that best meets the requirements of your app.

Thanks for your response. I am not familiar with using filters - is this the only solution do you think? My JS approach above works but only the first time in a session for some reason..

It could be because of Turbolinks, which prevents the document.ready event from firing when transitioning between pages, so the event handler never gets bound again until you do a page refresh.

@MathDaniel You must bind the event handler on Turbolinks' events (if user clicks a Turbolink to get to the page), as well as document.ready (if page is refreshed, or user lands on page directly). Here's a quick example I wrote:

jquery - Attempting to allow keyboard/letter scroll in boostrap dropdo...

jquery ruby-on-rails drop-down-menu keyboard-events