Jerome
Jerome

Reputation: 6189

Javascript output used for a rails condition

The following javascript returns the viewport of a browser:

<script>
  $(document).ready(function(e) {
    showViewportSize();    
  });
  $(window).resize(function(e) {
     showViewportSize();
  });
  function showViewportSize() {
     var the_width = $(window).width();
     var the_inner_width = window.innerWidth;                   
     $('#width').text(the_width);
     $('#inner_width').text(the_inner_width)
  }
</script>

The browser can display the value via

<span id="inner_width"> Resize me </span>

How can width or innerWidth be invoked in a rails condition within a view file, assuming one wants to generate an image_tag based on the initial viewport width:

<% if width > 1440 %>
  <%= image_tag(...
<% elsif width <= 1440 && width > 1200 %>
  <%= image_tag(...
<% else %>
  <%= image_tag(...
<% end %>

Upvotes: 0

Views: 45

Answers (1)

max
max

Reputation: 102046

You would need a time travel device for this to even be remotely possible. The view is rendered on your server long before the page is even sent to the client. The only way the server would know the viewport size is if you sent it in the request. And thats not exactly ideal as the viewport size may change after the fact. The javascript is executed much later on the client when it gets the response from the server.

The solution is really simple - just provide all the available paths to the client and let it choose what image size to use.

Nowadays <img> tags can be made responsive with the srcset and sizes attributes. This is an example from MDNs excellent tutorial on responsive images:

<img srcset="elva-fairy-480w.jpg 480w,
             elva-fairy-800w.jpg 800w"
     sizes="(max-width: 600px) 480px,
            800px"
     src="elva-fairy-800w.jpg" alt="Elva dressed as a fairy">

srcset defines a comma separated list of sources and sizes defines the media rules that choose what size is used.

A quick and dirty rails conversion would be:

<%= img_tag('elva-fairy-800w',
  srcset: ["480w", "800w"].map {|s| image_path('elva-fairy-' + s) " #{s}" }.join(', ')
  sizes: "(max-width: 600px) 480px, 800px",
  alt: "Elva dressed as a fairy"
)%>

Upvotes: 1

Related Questions