Google charts does not always load in first attempt - ruby-on-rails

I ask advice. Google chart is not always loaded on the first attempt ... how to solve this problem?
demo
view:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Time', 'TempC'],
<% #data.css("hourly").each do |hrly| %>
['<%= hrly.css("time").text %>',<%= hrly.css("tempC").text %>],
<% end %>
]);
var options = {
title: 'Temperature forecast'
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<div id="chart_div" style="width: 100%; height: auto;"></div>
controller
class WwoController < ApplicationController
def weather
require 'nokogiri'
url = "https://api.worldweatheronline.com/premium/v1/weather.ashx?q=59.94%2C30.31&num_of_days=4&key=***********************************"
#data = Nokogiri::XML(open(url))
end
end

If you use turbolinks, try to disable it in that page, because I have similar problems with google maps apis
to disable turbolinks you can add this to your application.html.erb
<body <%= yield(:body_attributes) %>>
then in your view.html.erb add this in first line
<%= content_for(:body_attributes, 'data-no-turbolink') %>
you can also disable turbolink with link_to
<%= link_to 'link_name', your_link_path, 'data-no-turbolink' => true %>
if you use rails/turbolinks 5
change data-no-turbolink into data-turbolinks and switch the boolean value
also try to put your javascript in the bottom. to make it loaded after the html dom.

Related

auto save javascript with rails

I created a localstorage for the form on rails, when I tried the js code above for the
<textarea id="text"></textarea> tag it worked,
but when I tried the code like this, <%= f.text_area :title, class:"quill_container", id:"text" %> it only managed to retrieve the key, the value couldn't be retrieved
javascript code
<script type="text/javascript">
$(function() {
if (localStorage) {
var content = localStorage.getItem("autoSave");
if(content) {
$('#text').text(content);
}
}

Google Map Javascript Only loads after refresh

Using Google Map API, I have embedded Google Map (Javascript) in my page. However, the map will only load after I refresh the page once.
I looked up on many past threads, to which many mentioned the caused related turbolinks.
I tried many of those but still it didn't work.
Application.html.erb
<%= yield %>
<%= javascript_include_tag "https://maps.googleapis.com/maps/api/js?libraries=places&key=#{ENV['GOOGLE_API_BROWSER_KEY']}" %>
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
<%= javascript_pack_tag 'application' %>
<%= javascript_pack_tag "map" %>
Show.html.erb
<div id="map"
style="width: 100%;
height: 300px;"
data-markers="<%= #markers.to_json %>"
></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=<%= ENV['GOOGLE_API_BROWSER_KEY'] %>&callback=initMap"
type="text/javascript"></script>
javascript/packs/map.js
import GMaps from 'gmaps/gmaps.js';
const mapElement = document.getElementById('map');
if (mapElement) {
const map = new GMaps({ el: '#map', lat: 0, lng: 0 });
const markers = JSON.parse(mapElement.dataset.markers);
map.addMarkers(markers);
if (markers.length === 0) {
map.setZoom(2);
} else if (markers.length === 1) {
map.setCenter(markers[0].lat, markers[0].lng);
map.setZoom(14);
} else {
map.fitLatLngBounds(markers);
}
}
Please let me know if you have any additional question or if you need anymore info.
Appreciate all your helps!

Starting owlCarousel in rails

I am new to rails and this is the first time I want to use a carousel in a web application. My carousel appears, but it does not auto-play.
This is what I have in my application.js :
//= require owl.carousel
$(function(){ $(document).foundation(); });
var owl = $('.owl-carousel');
owl.owlCarousel({
items:5,
loop:true,
margin:10,
autoplay:true,
autoplayTimeout:1000,
autoplayHoverPause:true
});
And this is from my view:
<div id="owl" class="owl-carousel">
<% #artists.each do |artist| %>
<div class="artist-card ">
<%= link_to artist, class: "poster" do %>
<%= image_tag artist.image.url(:thumb) %>
<% end %>
<div class="artist-info ell glassy-bg padmy padlx">
<div class="artist-card ">
<h6><%= artist.name %> <span>(<%= artist.instrument %>)</span></h6>
</div>
</div>
</div>
<% end %>
</div>
Is there also a way to display every artist from my database in the carousel? I've seen that the default number of items for the carousel is 5. Can I make it dynamic ?
I managed to solve the issue. Here is what I've done:
(function ($) {
$(document).ready(function() {
if ($('.carousel .owl-wrapper-outer').length === 0) {
var owl = $('.carousel').owlCarousel({
items:5,
loop:true,
margin:10,
autoPlay:1000,
autoplayHoverPause:true,
responsive: true,
responsiveRefreshRate : 200,
responsiveBaseWidth: window,
});
$('.carousel').hover(function() {
owl.trigger('owl.stop');
}, function(){
owl.trigger('owl.play', 1000);
});
}

How to load a Rails View inside an infobox using gmaps4rails & JQuery Ajax?

I would like to know how can I load a Rails View inside a Infobox opened by Gmaps4Rails.infobox.
I did this way and work fine. O secret is put serviceObject, in some example show google_object.
<% content_for :scripts do %>
<script>
Gmaps4Rails.callback = function() {
for (var i = 0; i < this.markers.length; ++i) {
google.maps.event.addListener(Gmaps4Rails.markers[i].serviceObject, 'click', function(){
$('#info').load('/messages');
$('#info').dialog("open");
});
}
};
</script>
<% end %>

Select all checkboxes

In my Rails app I've created a set of checkboxes as follows:
<div class="form_row">
<label for="features[]">Features:</label>
<% ['scenarios', 'news', 'role_profiles', 'private_messages', 'chatrooms', 'forums', 'polls'].each do |feature| %>
<br><%= check_box_tag 'features[]', feature, (#features || {}).include?(feature) %>
<%= feature.humanize %>
<% end %>
</div>
I'd like to know how to create a button that would "Select All".
Using jQuery;
<script type="text/javascript">
function selectAll(){
$("input:checkbox").each(function(){
$(this).attr('checked', true);
});
return false;
}
</script>
HTML button:
Select All
If you use the Prototype JS, you might find this blog post helpful. It gives a fairly concise way to perform a select all.
http://www.ryboe.com/2008/07/10/select-all-checkboxes-with-prototype-js.html
In your view you could use the following snippet to create a "Select All" link:
<%= link_to_function("Select All","checkboxes.each(function(e){ e.checked = 1 })") %>
In addition, you'd need the following Javascript code somewhere on the same page (or maybe even abstracted out to the public/javascripts/application.js file
var checkboxes = [];
checkboxes = $$('input').each(function(e){ if(e.type == 'checkbox') checkboxes.push(e) });
var form = $('options'); /* Replace 'options' with the ID of the FORM element */
checkboxes = form.getInputs('checkbox');
Here's the full source of a working example, if this doesn't work you might need to check to make sure your JS libraries are loading properly.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="http://www.google.com/jsapi" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
var checkboxes;
google.load("prototype", "1.6");
google.setOnLoadCallback(function(){
checkboxes = [];
checkboxes = $$('input').each(function(e){ if(e.type == 'checkbox') checkboxes.push(e) });
var form = $('options'); /* Replace 'options' with the ID of the FORM element */
checkboxes = form.getInputs('checkbox');
});
</script>
</head>
<body>
<form id="options">
<fieldset><input type="text" value="test"></fieldset>
<fieldset><input type="checkbox" value=0> 0</fieldset>
<fieldset><input type="checkbox" value=1> 1</fieldset>
<fieldset><input type="checkbox" value=2> 2</fieldset>
<fieldset><input type="checkbox" value=3> 3</fieldset>
</form>
Select All
</body>
</html>
I think you can use query like that
<script>
$('#check_all').on("click", function(){
var check = $('input[type="checkbox"]');
check.prop("checked", !check.prop("checked"));
});
</script>
and the html will be something like
<%= button_tag 'select / unselect all', id: 'check_all', class:'b' %>

Resources