Reputation: 19
Here is a rails controller redirect statement.
redirect_to "controller_action_path", error: err.to_s
The statement generates the following HTML in the browser's page source.
<div class="alert alert-danger alert-error" role="alert">"Your alert here"</div>
Problem: How do you create focus around the flash response message that appears at the top of the page. Attempted Solutions(s):
<% if flash[:error] %>
<%= javascript_tag do %>
$('.alert-danger').focus();
<% end %>
<% end %>
This works if the HTML element has an id tag. Perhaps if the HTML element has a class too. It seems as if static elements can receive the focus, but, since the flash error message is generated by the rails framework and is a dynamically generated element, either it has not rendered on the form at the time focus is attempted to be applied, or it cannot find the element in the page's HTML. The later does not appear to be the situation since the debugger returns the HTML for $('.alert-danger').focus();
Upvotes: 0
Views: 536
Reputation: 2575
Rails generates static html and sends it to the client, so anything Rails generates is rendered at the same time as all other HTML.
Try changing your controller code to redirect_to "controller_action_path", alert: err.to_s
and change your condition wrapping the jQuery function to <%= if flash[:alert] %>
. :error
is not a valid option for redirect_to
http://api.rubyonrails.org/classes/ActionController/Redirecting.html
I also don't think the conditional on the jQuery is necessary. If there's no error then there should be no visible tag with that error class anyway.
Also $.focus()
doesn't work on every element by default https://api.jquery.com/focus/
Upvotes: 0