Javascript clock function not running on Rails app - javascript

First real time I've tried to use Javascript in a Rails app, but nothing outside of alerts seem to be working for me.
What I'm trying to do is get this simple clock to run on my Rails app, pretty much copying the code where I thought it was supposed to go, but nothing's working and all my searches are either too specific or don't seem to work.
I want the clock to be available sitewide but I've also tried organizing it onto specific controllers and their views with the same amount of luck.
application.js
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require bootstrap-sprockets
//= require_tree ./sitewide
apps/assets/javascripts/sitewide/pages.js
function startTime() {
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML = h+":"+m+":"+s;
var t = setTimeout(function(){startTime()},500);
}
function checkTime(i) {
if (i<10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
application.html.erb
<!DOCTYPE html>
<html>
<head>
<title>Clawk</title>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
</head>
<body>
<%= render 'shared/navbar' %>
<div class="container-fluid">
<%= render 'shared/sidebar' %>
<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
<div id="txt"></div>
<%= yield %>
</div>
</div>
</body>
</html>

You have the JavaScript in place, but you are not actually calling the startTime() function. Note in the example it is called via an onload attribute on body: <body onload="startTime()">
With Rails, you could add this to the end of your pages.js file:
$(document).on('page:load', function() {
startTime();
});
This will execute the code within the function on page load (and will be compatible with turbolinks).

Related

How to create a guided tour in Rails with gem 'intros-rails'

Been working on this for a few days, I'm trying to use gem "introjs-rails" to create a guided tour in rails. https://github.com/heelhook/intro.js-rails. A few differences between whats below and what the guide asks for are the guide wants '//= require introjs' to be put in application.js, but I get a Javascript error of 'introJs().start(); is undefined variable' so I put '//= require introjs' in the 'Intro.js' file instead and that seems to fix it. But when I start up the page, I'm still not getting a pop up message to appear.
Application.html.erb
<head>
<title>Workspace</title>
<%= stylesheet_link_tag 'introjs', 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'intro', 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
Application.scss
/*
*= require introjs
*= require_tree .
*= require_self
*/
Index.html.erb
<h1 data-step="1" data-intro="This is a tooltip!">This is a Tool Tip!</h1>
Intro.js
//= require introjs
introJs().start();
Introjs.css
*= require introjs
Try the following:
Index.html.erb:
<a class='introduction-farm' href='#' data-intro='Hello step one!'></a>
Intro.js:
introJs(".introduction-farm").start();
As you suggested in the comment, loading the script too earlier was the source of the issue for you : setTimeout(function() { introJs().start(); }, 3000);
For your CSS issue, most likely jQuery was not referenced, in which case you need to include it before IntroJS, bootstrap:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

Percentage Loading Time in angular js with $http request

I am using angular with rails application
I have a demo app. I need to show response time required to load a response in angular
As an example.
I am loading a response of array of 100 k elements. I want to show percentage start from 0% and increment as response load. When full response loaded then it completes response time 100%
Details of using files
/app/views/layouts/application.html.erb
<!DOCTYPE html>
<html>
<head>
<title>Anguler</title>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
</head>
<body>
<%= yield %>
</body>
</html>
/app/views/pages/index.html.erb
<div ng-app="myApp" ng-controller="customersCtrl">
<ul>
<li ng-repeat="x in myData">
{{ x }}
</li>
</ul>
</div>
/app/controllers/pages_controller.rb
class PagesController < ApplicationController
def index
#arr = []
for n in 1..100000
#arr.push(n)
end
return render json: #arr
end
end
/app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
end
/assets/javascripts/application.js
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require angular.min
//= require custom.min
/assets/javascripts/custom.js
var app = angular.module('myApp');
app.controller('customersCtrl', function($scope, $http) {
$http.get("/").then(function (response) {
$scope.myData = response.data.records;
}
});
Let me know how it could be possible to showing loading percentage time in percentage
Many Thanks in advance
angular-loading-bar is a good plugs to help you implement it.
you can use this lib for here is best example for you.
http://nervgh.github.io/pages/angular-file-upload/examples/image-preview/

Rails js files & Page specific js

On rails I put all the JavaScript files into application js file.
//= require jquery
//= require jquery_ujs
//= require dropzone
//= require jquery.cookie
//= require toastr
//VENDOR JS BEGINS
//= require pace/pace.min
//= require modernizr.custom
//= require jquery-ui/jquery-ui.min
//= require boostrapv3/js/bootstrap.min
//= require jquery/jquery-easy
//= require jquery-unveil/jquery.unveil.min
//= require jquery-bez/jquery.bez.min
//= require jquery-ios-list/jquery.ioslist.min
//= require jquery-actual/jquery.actual.min
//= require jquery-scrollbar/jquery.scrollbar.min
//= require bootstrap-select2/select2.min
//= require switchery/js/switchery.min
//= require imagesloaded/imagesloaded.pkgd.min
//= require jquery-isotope/isotope.pkgd.min
//= require classie/classie
//= require codrops-stepsform/js/stepsForm
//= require bootstrap-datepicker/js/bootstrap-datepicker
Then I call javascript in the head of application.html.erb as;
...
<head>
..
<%= javascript_include_tag 'application' %>
..
</head>
...
Then I check the speed of the website and I am suggested to take this JS call to body. I know I should BTW. But the problem is with the page specific JS code.
Imagine I have home.html.erb where users select date. So I put datapicker code into this page.
If I take <%= javascript_include_tag 'application' %> into at the bottom of body, this time because the jquery & datepicker not loaded yet so page specific JS gives no method error
What would be the best approach?
Before body close tag and just after <%= javascript_include_tag 'application' %>
add <%= yield :page_scripts %>
Then anywhere (usually on top) in a specific view set your scripts with:
<% content_for :page_scripts do %>
<script>alert( "My nice scripts..." );</script>
<% end %>
There is a very good answer to this at http://brandonhilkert.com/blog/page-specific-javascript-in-rails/.
Basically, you want to open your app/views/layouts/application.html.erb and convince it to give you controller and view information each time it renders a page. To do so you change the body tag from
<body>
<%= yield %>
</body
to
<body class="<%= controller_name %> <%= action_name %>">
<%= yield %>
</body>
So, when rails renders the body tag it will now add a class for the controller and one of the actions in the controller.
Say you have a controller called static_pages, and the static_pages controller has
def home
end
When rails renders the view/page home it will now add to the body tag a class of static_pages and a class of home.
<body class="static_pages home">
the home view is rendered here
</body>
This will be a site wide change, so if you go to an index page/view from the users controller the body tag would be:
<body class="users index">
the index view is rendered here
</body>
Now, make a file called vendor/assets/javascripts/jquery-readyselector.js containing:
(function ($) {
var ready = $.fn.ready;
$.fn.ready = function (fn) {
if (this.context === undefined) {
// The $().ready(fn) case.
ready(fn);
} else if (this.selector) {
ready($.proxy(function(){
$(this.selector, this.context).each(fn);
}, this));
} else {
ready($.proxy(function(){
$(this).each(fn);
}, this));
}
}
})(jQuery);
That file must be properly referenced in application.js
...
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require jquery-readyselector
//= require_tree .
Once all that is done you can test it by making a simple alert specific to the view you want test like so:
// app/assets/javascripts/static_pages_home.js
$(".static_pages.home").ready(function() {
return alert("You should only see this on the static pages home page.");
});
// app/assets/javascripts/user_index.js
$(".users.index").ready(function() {
return alert("You should only see this on the users index page.");
});
You could also make a script controller specific by not referencing the action.
$(".users").ready(function() {
return alert("You should only see this on a users controller controlled page.");
});
You can also have a look at Page-specific Javascript for Rails done right. This is worth looking!
Installation
After installation. Let's look at sample code.
var ArticlesController = Paloma.controller('Articles');
ArticlesController.prototype.edit = function(){
// Handle edit article
};
That means that if you have Articles controller's edit action page. Then only the javascript will be triggered. This will not be triggered in other controller actions.

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?

Rambling-slider-rails shows only blank screen

I'm making an app using Rails 4.0.1 with Ruby 2.0 and I'm running into trouble installing the "Rambling slider" image carousel from here.
Here's the portion of the gemfile:
...
gem 'paperclip'
gem 'rambling-slider-rails', :git => 'https://github.com/gonzedge/rambling-slider-rails'
gem 'uglifier', '>= 1.3.0'
...
I ran bundle install and, following the instructions, put a reference to jquery.rambling.slider in my manifest files.
My app/assets/javascripts/application.js file:
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require jquery.rambling.slider
//= require_tree .
My app/assets/stylesheets/application.css file:
/*
*= require jquery.rambling.slider
*= require_self
*= require_tree .
*/
I included the link tags in app/views/layouts/application.html.erb like so:
...
<%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true %>
<%= javascript_include_tag "application", "data-turbolinks-track" => true %>
<%= stylesheet_link_tag 'jquery.rambling.slider' %>
<%= javascript_include_tag 'jquery.rambling.slider' %>
<%= csrf_meta_tags %>
...
Then added some dummy images and the invoking javascript in the actual view accordingly:
<div id="slider">
<%= image_tag "lorem1.jpeg" %>
<%= image_tag "lorem2.jpeg" %>
<%= image_tag "lorem3.jpeg" %>
</div>
<script>
$(window).load(function(){
$('#slider').ramblingSlider();
});
</script>
But all that appears a simple 1'2'3 on the page.
I know that the images are referenced correctly because when I comment out the script in the view file, the 3 images appear with no problems.
The developer tools in Chrome only show that there is a single warning saying "event.returnValue is deprecated. Please use the standard event.preventDefault() instead." at jquery.js?body=1:5375. (I can show this line too if you need it) This warning only appears when the script is uncommented. As soon as I comment it out, the warning goes away.
Any help would be much appreciated. Thanks in advance!
The problem you mentioned(1,2,3 links) occurs because the theme effect was not included, You can include this by adding a div with "theme-default" class, present in the .css file of rambling-slider. For this to work you also need to add the themes folder in stylesheet & images folder of your application
<div id="wrapper">
<div class="slider-wrapper theme-default">
<div class="ribbon"></div>
<div id="slider" class="ramblingSlider">
<%= image_tag "lorem1.jpeg" %>
<%= image_tag "lorem2.jpeg" %>
<%= image_tag "lorem3.jpeg" %>
</div>
</div>
</div>

Categories

Resources