How to get the sharebox jQuery plugin to work with Rails - javascript

I have downloaded the jquery sharebox from the following site and added what i believe to be the correct code to my app but i am unable to get it to work. I am getting the error messages that
Error: TypeError: $(...).sharebox is not a function.
http://www.jqueryscript.net/social-media/Simple-Clean-Social-Share-Plugin-with-jQuery-sharebox.html
_post.html.erb
<h2><%= link_to_unless_current post.title, post %></h2>
<%= simple_format post.body %>
<div class="demo"></div>
<div id="disqus_thread"></div>
<script type="text/javascript">
/* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
var disqus_shortname = 'cathjonesblog'; // required: replace example with your forum shortname
/* * * DON'T EDIT BELOW THIS LINE * * */
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript>Please enable JavaScript to view the comments powered by Disqus.</noscript>
comments powered by <span class="logo-disqus">Disqus</span>
<script>
$(document).ready(function(){
$('.demo').sharebox({
services : "facebook twitter google+ linkedin"
});
});
</script>
application.js
//= require jquery
//= require jquery_ujs
//= require foundation
//= require_tree .
//= require jquery.sharebox
$(document).foundation();
application.css
*= require_self
*= require foundation_and_overrides
*= require jquery.sharebox.css
I have placed the js file in my apps javascript directory and the cs files in the stylesheets folder and created an icons folder in the root for the images.
Any help would be greatly appreciated.
Thanks

It sounds like this line:
$('.demo').sharebox({
Might be above this line in the dom:
<script src='/assets/jquery.sharebox.js?body=1'></script>
Dependent javascript files need to be loaded in the right order - eg jquery.sharebox.js calls functions in the jquery library, so the jquery library has to be loaded first. In your case the sharebox plugin has to be loaded before you call .sharebox on that element.
If that isn't the issue, check the console for errors, a js file might not have loaded properly.

Related

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.

$ is not defined, Uncaught ReferenceError while using Select2 plugin with Rails

I'm trying to use the Select2 plugin to add a search bar to my select box.
I get the following error when looking at the page console :
Uncaught ReferenceError: $ is not defined
Searching different questions here led me to believe this error happens because the jQuery javascript is not included or put before the script is called. But I still could not find a way to make it work. How can I fix this error and make the select2 plugin work?
Here is the application.js file :
//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require jquery-fileupload/basic
//= require jquery-fileupload/vendor/tmpl
//= require select2
//= require tinymce
//= require turbolinks
//= require_tree
I've tried rearranging the order of select2 in the application.js file in many different ways with no success (I tried to make sure jQuery was loaded right before Select2).
Here is the index.html.haml file :
%select{:id => "test"}
- #lamps.each do |lamp|
%option{:value => "1"}= lamp.brand + ' ' + lamp.category + ' ' + lamp.lamptype + ' (' + lamp.cct.to_s + 'K)'
:javascript
$(document).ready(function() { $("#test").select2(); });
Here is the application.html.haml file :
!!! 5
%html
%head
%title= t('.lspdd_light_spectral_power_dis')
%meta{:name => "viewport", :content=>"width=device-width, user-scalable=no"}
= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true
= javascript_include_tag "application", "data-turbolinks-track" => true, :defer => "defer"
= javascript_include_tag "d3.min.js", :defer => "defer"
= csrf_meta_tags
Additionnal information :
Rails version : 4.0.3
ruby 1.9.3p484 (2013-11-22 revision 43786) [x86_64-linux]
Thank you!
Edit #1:
Adding the a screenshot of the information displayed by the network dev-tool.
http://imgur.com/QJGCM2b
If I understand correctly the application-ea826f14bc5ea6f6976b187ce8d3008e.js file includes everything mentionned in the application.js file?
dont use //= require_tree if you already include all you scripts manualy. this can be the cause of errors. remove this string and try to reload page
p.s
i also think what you are using incorrect sintax
//= require_tree
correct version contain dot
//= require_tree .
p.p.s.
not about your main question, but you are using old version of ruby. check the newer
one more important thing what i didn't mentiond before. you are using defer="defer" attribute for deffering main script loading. inline javascript what you type on page loaded BEFORE main scripts

Javascript clock function not running on Rails app

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).

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?

Why are js files in my rails asset pipeline not being compiled?

I am experiencing a problem similar to this question:
Rails asset pipeline not including required files in application.js manifest However, that question was closed, so I am re-asking it, but with the specifics of my situation.)
Environment:
Ruby 2.0.0, Rails 3.2.8, OSX 10.7.5, Chrome 28.0.1500.95
The main problem I am experiencing
Files placed in "/app/assets/javascripts" do not appear to be compiling to or appearing in "/public/assets"
An Example
If I place a file such as this test.js file in app/assets/javascripts:
alert("Hello!");
and then reload a page in my app, this alert should appear. (I am replicating what Ryan Bates does in his Railscast on the Asset Pipeline at ~6:30 into the video) However, no alert appears.
Debugging attempts
Some tests I did to try to debug this.
(As recommended by #Aidan below) If I "rm -rf public/assets", then
add "javascript_include_tag 'test'" to my layout, the alert does
appear. However, maybe because I'm a n00b, I don't know how that
helps me debug the problem.
If I add //= require_test to app/javascripts/application.js to my
manifest file, this does not result in the alert appearing.
My manifest file (app/javascripts/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 vendor/assets/javascripts of plugins, if any, 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
// the compiled file.
// removed /sitewide from require_tree
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require_tree .
My application.rb file
# Enable the asset pipeline
config.assets.enabled = true
Rails console output for "y Rails.application.config.assets.paths"
"/Users/Anders/Dropbox/dev/suggestion-box-app/app/assets/images",
"/Users/Anders/Dropbox/dev/suggestion-box-app/app/assets/javascripts",
"/Users/Anders/Dropbox/dev/suggestion-box-app/app/assets/stylesheets",
"/Users/Anders/.rvm/gems/ruby-2.0.0-p195#suggestion-box-app/gems/coffee-rails-3.2.2/lib/assets/javascripts",
"/Users/Anders/.rvm/gems/ruby-2.0.0-p195#suggestion-box-app/gems/jquery-rails-3.0.4/vendor/assets/javascripts"
My views/layouts/application.html.haml file
!!! 5
%html
%head
%meta{:charset => "utf-8"}/
%meta{:content => "width=device-width", :name => "viewport"}/
%meta{:content => "yes", :name => "apple-mobile-web-app-capable"}/
%title My App
%script{:type=>"text/javascript", :src=>"//use.typekit.net/wjb6ybj.js"}
:javascript
try{Typekit.load();}catch(e){}
= stylesheet_link_tag "screen", :media => "all"
= csrf_meta_tags
= javascript_include_tag "application"
%body
#container
= render "layouts/flashes"
= yield
= render "layouts/footer"
Source from an app page viewed in localhost:3000
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta content='width=device-width' name='viewport'>
<meta content='yes' name='apple-mobile-web-app-capable'>
<title>My app</title>
<script src='//use.typekit.net/wjb6ybj.js' type='text/javascript'></script>
<script>
try{Typekit.load();}catch(e){}
</script>
<link href="/assets/screen.css?body=1" media="all" rel="stylesheet" type="text/css" />
<meta content="authenticity_token" name="csrf-param" />
<meta content="FqMtH+rs6or9HRx+RL4bWpQyLTNPM8BKLrcf/xZknP8=" name="csrf-token" />
<script src="/assets/application.js?body=1" type="text/javascript"></script>
</head>
<body>
<div id='container'>
....
</div>
</body>
</html>
What I see when viewing "localhost:3000/assets/application.js"
/*!
* jQuery JavaScript Library v1.9.1
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2005, 2012 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2013-2-4
*/
(function(e,t){function P(e){var t=e.length,n=b.type(e);return b.isWindow(e)?!1:e.nodeType===1&&t?!0:n==="array"||n!=="function"&&(t===0||typeof t=="number"&&t>0&&t-1 in e)}function B(e){var t=H[e]={};return b.each(e.match(E)||[],function(e,n){t[n]=!0}),t}function I(e,n,r,i){if(!b.acceptData(e))return;var s,o,u=b.expando,a=typeof n=="string",f=e.nodeType,c=f?
[...remainder of jquery excluded]
Should I not see the test.js file here?
Any suggestions as to what the problem might be? Is there any additional info I can provide to help debug this issue? Thanks for any help!
The problem appears to have been related to my rails/gem versions. After updating from Rails 3.2.8 to Rails 3.2.14 (which also required updating the rack gem from 1.4.1 to 1.4.5) the issue was resolved and items in assets/javascripts are now being compiled/added to public/assets. Note that I created a completely new gemset as part doing this, so the issue may have had nothing to do with the Rails version and simply was a questions of a "corrupted" gem set that needed to be re-created.
Rails will compile all the targets listed in config.assets.precompile. These targets will be compiled to public/assets/. That config item already includes "application.js" and other some targets, so you need to add any other targets you want to be precompiled to public/assets/. The source file to be compiled for any particular target are automatically computed based on the name of the target; e.g., a target of test.js would be compiled from app/assets/javascripts/test.js or from app/assets/javascripts/test.js.coffee, whichever exists.

Categories

Resources