Question

I want to dynamically display a list of items, but the number of items by row depends on the width of the screen. the number inside each_slice depends on the screen size... if large screen:

<% @posts.each_slice(3) do |s| %>
  <div class="row">
    <% s.each do |p| %>  
     <div class="small-12 medium-6 large-4 columns">

if medium screen:

<% @posts.each_slice(2) do |s| %>
  <div class="row">
    <% s.each do |p| %>  
      <div class="small-12 medium-6 large-4 columns">

Anyone knows how to have a js variable in

each_slice("javascript vairable") 

Thank you

Was it helpful?

Solution

I found a way. I used Jquery to check the size of the window with: (coffee script)

n=2
if $('body').width() > 1025
  n = 3
if $('body').width() > 640
  $(".break:nth-child("+n+"n").addClass "row"

the html.erb looks like this:

<div class="row">
  <% @posts.each do |p| %>
    <div class="break">
      <div class="small-12 medium-6 large-4 columns">

and then with jquery I select the nth div and add a class row. It is not prefect but it works.

OTHER TIPS

It's not possible for JavaScript to interact with your ERB the way you're describing. The server doesn't know or care what the screen size of the client is.

You're using ZURB Foundation markup, right? If you REALLY want the server to be changing the markup based on screen size, consider using Foundation's Interchange functionality.

You'd need to reference a separate URL for each screen size that you're targeting. (Either via a URL parameter or create a separate action for each size.) Rails would output different markup depending on the URL that Interchange calls.

This really sounds like a job for CSS media queries. Judging by the CSS class names you are already using some sort of grid system.

<% @posts.each do |s| %>
  <div class="small-12 medium-6 large-4 columns">

Then in CSS:

@media (screen and max-width: 800px) {
  .medium-6 {
    width: 200px;
  }
}

@media (screen and max-width: 1000px) {
  .large-4 {
    width: 400px;
  }
}

You'll have to fiddle with the width values to get the desired effect.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top