grabury
grabury

Reputation: 5559

Adding javascript to a rails app page

I want to hide and show 2 links in my rails app

<a href="mailto:[email protected]", class="send_email">Invite</a>
<a href="", class="email_sent">Undo</a>

In my css

.email_sent{display: none;}

I added this to the bottom of the page

<%= javascript_tag do %>
 $(function(){
  $('.send_email > a').click(function(){
   $('.send_email').hide();
   $('.email_sent').show();
  });
  $('.email_sent > a').click(function(){
   $('.send_email').show();
   $('.email_sent').hide();
  });
 });
<% end %>

In console I get the following error

Uncaught ReferenceError: $ is not defined(anonymous function)

The page's source shows this

<script>
//<![CDATA[
$(function(){
$('.send_email > a').click(function(){
$('.send_email').hide();
$('.email_sent').show();
});
$('.email_sent > a').click(function(){
$('.send_email').show();
$('.email_sent').hide();
});
});
//]]>
</script>

How do I fix the javascript?

Upvotes: 0

Views: 31

Answers (2)

Kamesh
Kamesh

Reputation: 1465

Your javascript code should be put after the following tag.

<%= javascript_include_tag "application" %>

Because the application.js file includes jQuery. your script must be loaded after the jQuery is successfully loaded. The above line of code includes application.js to your web page.

Upvotes: 0

ethyl.bradtke
ethyl.bradtke

Reputation: 199

$ variable defined in JQuery library, so you should include it to your page before. Check that assets/javascripts/application.js includes this library.

FYI: your a tags has commas it can cause any rendering problems. Remove it.

Upvotes: 1

Related Questions