Javascript not loading properly using rails 3.1 - javascript

I'm using rails 3.1.0, coffee-rails 3.1.0, and therubyracer 'v8'. I see the following error when I try to inspect the compiled javascript using firebug...
<script type="text/javascript" src="/assets/application.js">
Reload the page to get source for: http://localhost:3000/assets/application.js
</script>
Inside app/assets/javascripts/post.js.coffee I have the following code:
$(window).resize ->
if $(window).width() <= 800
$(".container").css('margin-left', '100px')
$(".left-slider").html("margin-left 100px")
else
$(".container").css('margin-left', '')
$(".left-slider").html("margin-left 0px")
In app/views/layouts/application.html.erb I'm using this line...
<%= javascript_include_tag "application" %>
Also, I don't know if this is relevant or not but before the error above popped up I was seeing stale javascript code in firebug.

Related

Adding javascript to a rails app page

I want to hide and show 2 links in my rails app
Invite
Undo
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?
$ 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.
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.

Including D3 in an ERB loop

I have a partial called _index.html.erb
<% metric_objects.each do |metric_object| %>
<% if metric_object.histogram.has_key? 0 %>
<%= javascript_include_tag 'iterative_metric_graph.js', metric_object %>
<% else %>
<!--Another type of graph-->
<% end %>
<% end %>
It is supposed to generate a D3 bar graph for each metric_object. When I open the page, I get the error "D3 is not defined" in the console.
iterative_metric_graph.js is a file in my app/assets/javascripts/active_admin folder.
It consists of the javascript code from this page: http://bl.ocks.org/mbostock/3943967 Nothing more than what is inside the script tags right now.
The issue is that D3 is not being included in iterative_metric_graph.js. I could resolve the error by putting the javascript graph code (from the link above) straight into _index.html.erb, and adding <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>, but I would much prefer to render a partial. How can I include D3 (from the web or from a file) in my javascript file?
To include D3 you can just download it and stick it in you app/assets/javascripts directory. Then add the following to your application.js file:
//= require d3.v3.min
Alternatively you could try to put it in vendor/assets/... but there's a little more work involved in getting that to play nice with the asset pipeline. (more info here: Rails asset pipeline: Standard way for including all /vendor/assets/javascripts/?)

SCRIPT5009: '$' is undefined , when adding scripts inside my partial view

I have a main view that render another partial view as follow:-
#Html.Partial("_PagedTable",Model)
I have define Scripts inside the _PagedTablepartial view as follow:-
<div id ="RackTable">
<script type="text/javascript">
$(document).ready(function () {
Currently the scripts inside the partial view is working well , but when i opened the F12 developer tool on IE and the firebug tool, there will always be the following error on the scripts , raised on the scripts that are defined inside the partial view:-
SCRIPT5009: '$' is undefined
Altohugh there is an error but users will not notice this error , since no error messages will be displayed (of course unless they open the F12 developer tool), and the scripts inside the partial view is working well. so what does this error indicates exactly ?
Are you sure the code within
$(document).ready(function () {
is being executed?
the error means jQuery not loaded, hence your script would not be able to execute
I have found similar problem from SO (such as IE10 and jQuery: SCRIPT5009: "$" is undefined), but they all seem to happen on IE but you mention it happen on firefox as well, so I would only suggest check if your jQuery is loaded properly or not.
Commonly, jQuery is referenced in your Layout page (MasterPage) only in the end of the file.
So, your partial view is coming before this, when jQuery wasn't loaded yet.
What is strange is the browser throws this exception, but jQuery still works.
Worth trying using Razor Sections:
<html>
<body>
[View]
[_PartialView]
#section Scripts {
<script type="text/javascript">
$(document).ready(function () {
// stuff
});
</script>
}
[_PartialView - END]
<!-- jQuery and other references -->
<script src="jquery.min.js"></script>
#RenderSection("Scripts", required: false)
</body>
</html>

The right way to include page-specific JavaScript in Rails

I want to include this, for example:
jQuery(document).ready(function($) {
$('#my-modal').modal(options)
});
In one specific place in a rails app. In my case the file is called views/modals/mymodal.html.erb. There and only there.
I can't figure out how to do that without getting it on all pages as would happen if I put it in assets.
These are some useful tricks
#1 with file js
Create file your.js for your javascript
call file your.js on specific your layout
remove //= require_tree . on application.js
add your.js to asset percompile on config/application.rb : config.assets.precompile += %w( your.js )
#2 put into specific file non layout (not recommended)
put your js script with javascript tag on mymodal.html.erb
#3 use if..else..
put your js script into layout/yourlayout.html.erb and use if.. else.. logic.
example :
<% if current_page?(yourspecific_path) %>
<script language="text/javascript">
your javascript here ..
</script>
<% end %>
Read more here about current_page?
Or use request.fullpath to get current full path
example :
<% if request.fullpath == yourspecific_path %>
<script language="text/javascript">
your javascript here ..
</script>
<% end %>
Read more here about request.fullpath
Also you can combine #1 and #3 if you want script put into file .js
cheers
Given the JS file you want to include is named my_modal.js:
Place your JS files placed in assets/javascripts in some directory inside of
assets/javascripts, for example application.
Change line //= require_tree . to //= require_tree application in your application.js (it prevents loading my_modal.js on every page).
Place your my_modal.js in assets/javasctripts
Add my_modal.js to config.assets.precompile array (config assets.precompile += ['my_modal.js']) in your application.rb.
Put javascript_include_tag 'my_modal' in the view you want this file included
You can go to Rails guides for reference.
One of the solution is to insert our javascript in to its own file: Reference Link
For example :
// app/assets/javascripts/alert.js
alert("My example alert box.");
And including this file only in the view we want it to execute:
<%# app/views/page/contact.html.erb %>
<%= javascript_include_tag "alert" %>
<h1>Contact</h1>
<p>This is the contact page</p>
And don’t forget to include your new file in the list of files to be compiled:
# config/environments/production.rb
config.assets.precompile += %w( alert.js )
Late to the party, but for anyone viewing this today I think I've come up with something better.
Punchbox Gem for Rails
With this, you can write code like:
class Post {
controller() {
// Runs on every action
}
index() {
// Runs on just the index action
}
}
Punchbox.on('Posts', Post);
(You can also create an object instead of a class. See the docs)
I've written about this much more in depth here: https://kierancodes.com/blog/page-specific-javascript-in-rails-4
jquery-readyselector is a plugin that "Extends $().ready() to provide a convenient syntax for page-specific script"
Install jquery-readyselector
Create some CSS classes
<body class="<%= controller_name %> <%= action_name %>">
Scope your javascript to your page
$("#my-modal").ready(function() {
$('#my-modal').modal(options)
});
More info in this answer How to load page specific rails 4 js files?

Gon doesn't work with .js files in Sinatra

In my head within layout.erb I included <%= include_gon %>
In main.rb I have written
require 'gon-sinatra'
Sinatra::register Gon::Sinatra
gon.test = "Test"
puts gon.test
The console outputs Test as expected.
However when I create a .js file and write something like console.log(gon.test) and I look in Firebug or Chrome Console, it says Reference Error: gon is not defined. Why is this happening? What should I do to fix this?
It turns out I have written <script><%= include_gon %></script> which makes it fail. <%= include_gon %> shouldn't be written inside <script> tags.

Categories

Resources