Sean Magyar
Sean Magyar

Reputation: 2380

rails triggering js action on reload

I have a rails4 app. I'd like to trigger some js events on page load, but only if user comes from a given page.

By default all the comment replies are hidden on the post#index page. If user clicks on a div then the corresponding replies become visible.

Now I want to have a given post_comment_reply div visible by default on page load, if a user comes to the page via clicking on the notification belonging to the post_comment_reply.

What is the preferred way in rails to do that?

js

$(document).on('click', '.open-post-comment-reply', function (event) {
  var post_comment_id = $(this).data('pcid');
  $('#post-comment-replies-' + post_comment_id).toggle();
});

Upvotes: 0

Views: 56

Answers (2)

toddmetheny
toddmetheny

Reputation: 4443

Setting a cookie would work, as suggested by another user. You could also check the request.referrer in rails to see where they came from.

Couple of ways to handle triggering the js from there. You could pass the referrer value to the js with something like:

<div class="some-class" data-referrer="<%= request.referrer %>">

Then in your js, if you're using jQuery:

if ($('.some-class').data('referrer') == 'whatever_url'){
  // run your code
}

You could also put a conditional directly in the view. Probably not as clean but something like:

<% if request.referrer == 'whatever_url' %>
  <script>
    // code to run
  </script>
<% end %>

Upvotes: 1

Vitali Mogilevsky
Vitali Mogilevsky

Reputation: 720

you can attach a cookie on the given page , in link onclick event, then delete it after showing the comments box.

Upvotes: 1

Related Questions