0

In my Ruby on Rails app, I would like to only load a modal when the user loads the page the first time.

I decided to use cookies and set cookie(user saw once the page) = true by setting it to this value after the page has been loaded.

This way, the user loads the page the first time, the views loads (cookie value still false), then the cookie is set to 'true' and so the second time he will load the page, it won't load the modal.

But it does not work. I think the cookie gets set before the view is loaded altough I have placed the code lines after respond_to , at the end of the contorller action showcase (see below).

controller 'deal'

def showcase   # load the page 
    @deal = Deal.friendly.find(params[:id])

    respond_to do |format|
      format.html # showcase.html.erb
      format.json { render json: @deal }
    end

    cookies.permanent[:modal_loaded_once] = true

  end  

view showcase.html.erb

//this will load the modal only once as the first time it is loaded the // cookie value is still 'false'
<% if @modal_loaded_once = false %>  
  <script>
     $(window).load(function(){
        $("a.modal:first").trigger("click");
    });
  </script>
<% end %>

EDIT: answer

$(window).load(function(){
    if ($.cookie("show_modal_shownNX1") == null) {
      $.cookie('show_modal_shownNX1', 'yes', { expires: 720, path: '/' }); 
      $("a.modal:first").trigger("click"); 

    }
  });
Mathieu
  • 4,587
  • 11
  • 57
  • 112
  • 1
    Check the cookie from javascript instead of using a "conditional script tag" as it can lead to caching issues. – max Feb 08 '16 at 19:33
  • why? is it faster for load page performance? – Mathieu Feb 08 '16 at 19:34
  • Simple answer, yes. The long answer is that if you use e-tags or fragment caching then the user will get the modal anyways and `@modal_loaded_once = false` could even be evaluted with a cookie belonging to another user. Also your javascript will not be minified by sprockets... – max Feb 08 '16 at 19:39
  • https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie – max Feb 08 '16 at 19:40
  • understand now, you're right. thanks, but have to say I'm rookie in javascript, could you offer an example of how you'd do this in javascript ? – Mathieu Feb 08 '16 at 19:42
  • http://stackoverflow.com/questions/15351911/rails-store-a-cookie-in-controller-and-get-from-javascript-jquery – max Feb 08 '16 at 19:44
  • thanks actually I opted not to use anything inside the controller and put everything in javascript. edited my answer. what do you think , do i avoid the pitfalls you were talking about? – Mathieu Feb 08 '16 at 19:52

0 Answers0