I’d like to know how to call a JavaScript function from within an <% if statement %> in a Rails view. I don’t really know if it’s even possible.
home.html.erb:
<script type="text/javascript">
function my_javascript_function() {
return false;
}
</script>
<!-- some code before -->
<% if my_javascript_function %>
<li>
<a href="/link/">
Link
</a>
</li>
<% end %>
<!-- some code after -->
UPDATE:
After Chen’s answer, I realized that what I was doing was wrong, and instead of using <% if statement %> to create my element, I’m just using jQuery for this now. The code ended up like this:
$(document).ready(function() {
if(/* my_conditions */) {
$('#my_list_element').prepend('<li><a href="/link/">Link</a></li>');
}
});
So, when the page is loaded, it creates my element from javascript (jQuery). In my case, I used .prepend() because I needed it to be the first element within the list.
I think you got it wrong.
Javascript is rendered on the client side, while the rails part is rendered on the server side. When the server tries to render your ‘if’ statement it does not know nothing about the javascript function.