Ideally your website design should be responsive and adapt to every screen but in reality there are certain elements that can't really do that. For example, I was implementing a dropdown menu in Bootstrap that would take the whole screen width and show different columns and elements; on a desktop/tablet it works well, but on a mobile screen where the columns are all stacked up it's not as good looking. You might also want to switch some elements between the desktop and mobile version of the menu in order to add a link to your app or something similar.

After Googling for a bit I haven't found anything, just suggestions to use js but without including code; I bet there are more elegant ways of rendering partials for different screen sizes in Rails, but I couldn't find any. What I've done is simply using the offsetWidth property of the document body to decide what partial to render. In the dropdown case, you should create an empty element with a unique id to hold the menu like

<ul id="menujs" class="dropdown-menu"></ul>

And then use js to select which set of links to render:

if (document.body.offsetWidth <= 481) {
   $('#menujs').append('<%=j render "layouts/mobile" %>');
 } else {
   $('#menujs').append('<%=j render "layouts/desktop" %>');

The j in <%=j is the Rails escape Javascript method included in the Javascript Helper; if you don't use it, you'll get an ILLEGAL token error when the partial is rendered. If performances are REALLY important for you, do some more research on append vs innerHTML vs HTML functions; in my case the 2.3ms of difference weren't an issue.

Blog Logo

Alessio Fanelli

I'm a full stack developer with a love for sports.



Alessio Fanelli

Stay Sharp.

Back to Overview