Andrey Drozdov
Andrey Drozdov

Reputation: 591

jQuery, forbid load page before script is done

On my website, I want to add some user-friendly scripts. First of all, I want to add some after click loading gif. When user is hitting link (before redirect) user see loading gif (for sec or less) and only then user redirecting. So, my html (with ruby code injection):

<% for post in Posts do %>
    <%= link_to post do %>
      <div id="post-<%= post %>">
        <div id="loading_gif" style="margin: 75px 0 0 125px; padding: 0 auto; display: block; visibility: hidden; height: 50px; width: 50px; position: absolute">
          <%= image_tag '/loading/main-loading.gif' %>
        </div>
        <%= post.theme %>
        <%= post.picture %>
      </div> 
    <% end %>
<% end %>

And my script:

<script>
  $("post-<%= post %>").click(function(){
    $('#loading_gif').css('visibility', 'visible');
    return true;
  });
  $.delay(1000);
</script>

With that script I have a problem: I still see the loading animation when I go back to page where I come from.

But I really don't understand how to let script to do his work, then pause (to show user that post is loading (for example for 1 or less seconds)) and only then to redirect to post.

Upvotes: 0

Views: 44

Answers (1)

Michał Młoźniak
Michał Młoźniak

Reputation: 5556

Try this:

<script>
  $("post-<%= post %>").click(function() {
    var href = $(this).parent().attr("href");
    $('#loading_gif').css('visibility', 'visible');

    setTimeout(function() {
      $('#loading_gif').css('visibility', 'hidden');
      window.location = href;
    }, 1000);

    return false;
  });
</script>

Upvotes: 1

Related Questions