Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
keep users from navigating away from a very important page
# in your layout
<%= stylesheet_link_tag'styles' %>
<%= javascript_include_tag :defaults %>
<%= yield :script %>
# ...
# in the view you don't want your user to navigate away from
# this is nice on very important forms or a multistep process/wizard kind of deal.
<% content_for :script do %>
<script type="text/javascript">
// set a global js var to control whether or not users see the "don't navigate away please" dialog
// set this var to false on links or forms that can navigate away from page in an onclick property
var confirmation_needed = true;
window.onbeforeunload = confirmExit;
function confirmExit(){
// if you return a string it will be displayed in between "don't navigate away"
// and "click Ok to navigate away or cancel to stay put" in the confirm dialog
return "Ahoy!\n\n You done doing this awesomely important task?";
<% end %>
# below is an example of a link that can navigate away from the page without the above confirm dialog
# note that we set confirmation_needed to false before we do a different confirm message.
<%= link_to "cancel what i'm doing", destroy_this_info_path, :onclick => "confirmation_needed = false; confirm('You are about to destroy all this info');"%>
# the "don't nav elsewhere" dialog will appear on all forms that try to submit also
# we have to again set confirmation_needed to false, I do this in the submit_tag helper:
<% form_tag create_somestuff_path do%>
<%= text_field_tag :somestuff, "somestuff" %>
<%= submit_tag "save", :onclick=>"confirmation_needed = false;"%>
<% end%>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment