javascript scroll not working - javascript

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!

Related

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
}

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.

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?

Hide element depending on value of if/else statement not working

I have a Rails app that uses the LinkedIn Javascript API to authenticate users. What I'd like to do is hide an element depending on whether the user is signed up or not. I've tried a few things:
Put the code with the if/else statement at the bottom of the HTML before </body>
Check to see if document.cookie is an empty string instead of a more specific if/else
However, neither of these has hidden the element. If I go into my browser's console and paste in my code after the page is finished rendering, the element hides. So I thought this was a JavaScript load issue, but I must be doing something wrong. Can anyone shed some light on this?
Here's the code I've tried, none of which works:
<%= content_for(:script_footer) do %>
<script type="text/javascript">
// if ($('span.IN-widget:contains("inSign in with LinkedIn")').length > 0) {
// $('#select').hide();
// } else {
// $('#select').show();
// }
if (document.cookie == "") {
$('#select').hide();
} else {
$('#select').show();
}
</script>
<% end %>
And my application layout:
<!DOCTYPE html>
<html>
<head>
<title>rdtrip</title>
<%= stylesheet_link_tag "application", :media => "all" %>
<%= yield(:linked_in) %>
<%= javascript_include_tag "application" %>
<%= csrf_meta_tags %>
</head>
<body>
<%= yield %>
<%= yield(:script_footer) %>
</body>
</html>
Wrap your jquery/javascript code with:
$(function(){
// your code here
});
The JavaScript is executed before the DOM is ready, so it can't find #select yet.
Wrap it in either:
$(document).ready( function() {
// code
});
Or:
$(function() {
// code
});

Google CDN Jquery load not working

I currently have an ugly array of separate javascript files in one of my layouts and I'm trying to clean it up using the Google CDN.
Current state (horrible I know):
...css...
<%= yield :head %>
<%= javascript_include_tag "https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js" %>
<script type="text/javascript" src="http://cdn.jquerytools.org/1.2.5/all/jquery.tools.min.js"></script>
<%= javascript_include_tag "https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js" %>
<%= javascript_include_tag "ui/jquery.ui.core", "ui/jquery.effects.core",
"ui/jquery.effects.highlight", "ui/jquery.ui.widget", "ui/jquery.ui.tabs",
"ui/jquery.ui.progressbar" %>
<%= javascript_include_tag "jquery.ui.stars.min", "application", "rails" %>
I tried replacing the 2nd from bottom tag (with the long list of files) with:
<%= javascript_include_tag "https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js" %>
I am getting no luck with that - it seems as if the google file is not there at all (I checked my page source and it is loaded). What am I doing wrong here?
I don't know how to translate it into RAILS but this simple HTML should do the trick.
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
if(typeof jQuery == 'undefined') {
//<![CDATA[
document.write("<script src='/includes/jquery-1.4.2.min.js' type='text/javascript'><\/script>");
//]]>
}
</script>
This would assume that your jQuery file is stored on /includes/jquery-1.4.2.min.js.
On Google's CDN failure, local copy will get fetched.
Sorry to dredge up an old post, but I'm not sure the question was actually answered.
I had a similar problem as you did, and the solution was actually quite simple: I was not including the CSS. You can do so through Google's CDN as well:
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/ui-lightness/jquery-ui.css" media="screen" rel="stylesheet" type="text/css" />
or
<%= stylesheet_link_tag 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/ui-lightness/jquery-ui.css' %>
Obviously this is for the ui-lightness theme; there are other themes available on the CDN (though not all of them). I'm sure you can find those with a quick Google search.

Categories

Resources