Adding javascript to a rails app page - javascript

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.

Related

Javascript code not working in Ruby on Rails

I was trying to do my front-end with this Codepen Template but when i'm trying to click on the signup button, it's not changing to signup form for which the code is in the index.js file, i've included hte index.js file in the login.html.erb but when i'm running the rails server the transition isn't working. My Rails Project, Codepen Template
Here is the javascript code in index.js
document.querySelector('.img__btn').addEventListener('click', function() {
document.querySelector('.cont').classList.toggle('s--signup'); });
Try changing the path of index.js Add this line in app.html for including index js file .
<%= javascript_include_tag "index" %>
Wrap your current JS code in app/assets/javascripts/application.js within a DOMContentLoadListener event listener:
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('.img__btn').addEventListener('click', function() {
document.querySelector('.cont').classList.toggle('s--signup');
});
});

Using Rails, how do I execute a javascript file on a specific page in the application?

I am attempting to load a javascript file onto my rails application, but only for a specific page in my application, not the homepage. How would I get my javascript file to load for a specific page is using rails.
The javascript I have now, located in programs.js in assets/javascript, looks like this:
document.addEventListener('DOMContentLoaded', (event) => {
let program = document.getElementsByClassName('program-name')
console.log(program)
})
Again, the code itself works fine. The problem is that it executes for the homepage, and not for any particular page that I want it to. How would I go about getting the code to execute for a specific page within my rails application?
Why wouldn't you add the javascript tag to the View you want it to run on?
If you wanted a bit better rendering speed, you could add a end-of-page yield to your layout and then specify your javascript in the View like this:
layout/application.html.erb
<!DOCTYPE html>
...
<%= yield(:scripts) %>
</body>
</html>
view/.../index.html.erb
<!-- regular view code here -->
...
<% content_for :scripts %>
<%= javascript_tag do %>
document.addEventListener('DOMContentLoaded', (event) => {
let program = document.getElementsByClassName('program-name')
console.log(program)
});
<% end %>
<% end %>
An other way is to do the following:
app/views/layouts/application.html.erb
<body class="<%= controller_name %> <%= action_name %>">
<!-- This will add your page's controller and action as classes, for example, "blog show" -->
Then, in your script file, you can do the following:
if($('body').is('.yourcontroller.youraction'){
// Do something
}

javascript scroll not working

I want my link to scroll down the page to the target content.
This is my script (inside the head tag):
<script type="text/javascript">
jQuery(document).ready(function($) {
$(".scroll").click(function(event){
event.preventDefault();
$('html,body').animate({scrollTop:$(this.hash).offset().top},1200);
});
});
</script>
And these are my links (inside the body tag):
<%= link_to 'Plataformas', root_path + '#plataformas', class: "scroll" %>
<%= link_to 'Contato', root_path + '#contato', class: "scroll" %>
This chunks of code are inside my application.html.erb.
Thank you in advance!
check $(this.hash).offset().top value;
console.log($(this.hash).offset().top);
look this!
My problem wasn't in the code above, but actually my application.js was missing the require_tree line so it wouldn't load the other js files. Though the answer below it's not the solution for my problem (and that's why I didn't select it) #yodfz_cn was very helpful, thanks!

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?

Javascript not loading properly using rails 3.1

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.

Categories

Resources