I just started a Rails 5 project, and on the homepage I'm supposed to have a video banner, muted, in loop autoplay. I'm using Turbolinks 5 and I don't know if I can keep it.
When I load the home page for the first time, everything works fine. But when I go to any other page, the sound of the home page video starts to play. And If I go back to the home, the sound start again, over the sound previously started.
And so I have multiple instance of the sound of the muted video playing at the same time.
Fun at first, nightmare after 5 seconds.
I've seen this issue: https://github.com/turbolinks/turbolinks/issues/177 , which is still open and have no practical solution in the comments.
Apparently it's not new, this post https://www.ruby-forum.com/topic/6803782 seems to talk about the same problem in 2015. The guy talks about disabling Turbolinks for the link that lead to that page. I can't do it, since my problem is on the home page.
This is due to Turbolinks caching a copy of the homepage DOM. Even though the video is not visible it still exists in the cache and so will play. (However, I'm not sure why it's not muted—this could be a browser bug :/)
I think Turbolinks could handle this by default, but in the meantime, here are a couple of options:
Solution 1: Disable Caching on the Homepage
To prevent Turbolinks from caching a copy of the homepage, you could disable caching for that page. For example, you could include the following in your layout's <head>:
<% if #turbolinks_cache_control %>
<meta name="turbolinks-cache-control" content="<%= #turbolinks_cache_control %>">
<% end %>
Then in your homepage view:
<% #turbolinks_cache_control = 'no-cache' %>
The downside is that you miss out on the performance benefits when the visitor revisits the homepage.
Solution 2: Track autoplay elements
Alternatively, you could track autoplay elements, remove the autoplay attribute before the page is cached, then re-add it before it's rendered. Similar to Persisting Elements Across Page Loads, this solution requires that autoplay elements have a unique ID.
Include the following in your application JavaScript:
;(function () {
var each = Array.prototype.forEach
var autoplayIds = []
document.addEventListener('turbolinks:before-cache', function () {
var autoplayElements = document.querySelectorAll('[autoplay]')
each.call(autoplayElements, function (element) {
if (!element.id) throw 'autoplay elements need an ID attribute'
autoplayIds.push(element.id)
element.removeAttribute('autoplay')
})
})
document.addEventListener('turbolinks:before-render', function (event) {
autoplayIds = autoplayIds.reduce(function (ids, id) {
var autoplay = event.data.newBody.querySelector('#' + id)
if (autoplay) autoplay.setAttribute('autoplay', true)
else ids.push(id)
return ids
}, [])
})
})()
This script gets all the autoplay elements before the page is cached, stores each ID in autoplayIds, then removes the autoplay attribute. When a page is about to be rendered, it iterates over the stored IDs, and checks if the new body contains an element with a matching ID. If it does, then it re-adds the autoplay attribute, otherwise it pushes the ID to the new autoplayIds array. This ensures that autoplayIds only includes IDs that have not been re-rendered.
Related
I'm trying to figure out how I can ReactiveList to display a related searches feature on the results page. It seems that my es app on appbaseio keeps adding links EVEN after the page has sat idle for a few minutes, NO USER INTERACTION at all.
This is my code for the ReativeList component
<ReactiveList
componentId="related-searches"
pages={1}
size={5}
stream={false}
showResultStats={false}
react={{
"and": ["SearchSensor"]
}}
onData={(res) => <a href="#" className="card-link"><li
className="list-inline-item">Link text</li></a>}
/>
I thought that pages, size and stream (and their settings) would stop the streaming (or whatever is causing it)?
You can use the defaultQuery prop on ReactiveList to make it show some default results (or related searches in your case) docs. For example:
<ReactiveList
...
defaultQuery={() => ({
match: {
authors: 'J.K. Rowling'
}
})}
/>
Demo
I'm running Angular 1.6 along with TurboLinks 5. For the most part, things are working well. I disabled TurboLinks cache and am manually bootstrapping Angular per some of the suggestions on this post: Using angularjs with turbolinks
I have run into one issue though where I have an $interval running within a service. When changing pages via TurboLinks, Angular bootstraps again and the service creates a new interval, but the old one continues to run! Every time a page change event occurs, a new interval is created and they keep piling on top of each other.
I tried destroying the angular app when a TurboLinks link is clicked (using the code below), but that seems to cause the whole Angular app to quit working. I also can't seem to get a reference to the older interval after a page reload.
var app = angular.module('app', []);
// Bootstrap Angular on TurboLinks Page Loads
document.addEventListener('turbolinks:load', function() {
console.log('Bootstrap Angular');
angular.bootstrap(document.body, ['app']);
});
// Destroy the app before leaving -- Breaks angular on subsequent pages
document.addEventListener('turbolinks:click', function() {
console.log('Destroy Angular');
var $rootScope = app.run(['$rootScope', function($rootScope) {
$rootScope.$destroy();
}]);
});
Without the $rootScope.$destroy() on the turbolinks:click event, everything else appears to be working as expected.
I know I could fire off an event here and kill the interval in the service, but ideally I'd like some way where this is automatically handled and ensured nothing is accidentally carried over between TurboLinks requests. Any ideas?
After a lot of trial and error, this does the job, but is not exactly what I'm looking for. Would like to hear if anyone else has any suggestions. It would be ideal if this could happen automatically without a service having to remember to cancel it's own intervals. Also accessing $rootScope in this manner just feels so dirty...
// Broadcast Event when TurboLinks is leaving
document.addEventListener('turbolinks:before-visit', function(event) {
console.log('TurboLinks Leaving', event);
var $body = angular.element(document.body);
var $rootScope = $body.injector().get('$rootScope');
$rootScope.$apply(function () {
$rootScope.$broadcast('page.leaving');
});
});
I'm then injecting $rootScope into my service as well as keeping a reference to the interval. Once it hears the page.leaving event, it cancels the interval:
var self = this;
self.interval = $interval(myFunction, intervalPoll);
....
$rootScope.$on('page.leaving', function() {
$interval.cancel(self.interval);
});
So this gets the job done... but would love to find a better way. Credit for accessing $rootScope this way came from here: How to access/update $rootScope from outside Angular
I work on Jquery Mobile/Phonegap app for android.
I´d like my app to "remember" that(if) the user has visited one of my pages. For example if he once visits "page1.html", this action should be cached in the phone memory, so that when the user opens the app again there should be possibility to navigate to this "page2.html" directly from "index.thml".
Please, if you have a code suggestion, tell me also how/where do I use it, because sometimes for starters like me it is realy hard to understand what to do with a little piece code.
Thank you very much!
You can use HTML5 local storage for this purpose.
Each time when a page is shown you can save/update the current page URL to a local storage variable, say 'lastVisit', as below:
$(document).on('pageshow', function (event, data) {
var currentPage = $('.ui-page-active').data('url');
localStorage.setItem("lastVisit", currentPage);
});
If you are not getting $('.ui-page-active').data('url'), then you can use $.mobile.activePage.attr('id') which will give you the current page id.
So next time, when the user opens the app again, you can check whether this local storage variable is set and can action accordingly.
The code will look like as below:
$(document).on('mobileinit', function(){
var lastVisit = '';
if(localStorage.getItem("lastVisit") != null){
lastVisit = localStorage.getItem("lastVisit");
}
if(lastVisit){
document.location.href = lastVisit;
}
});
You can use these codes in the header section scripts.
As the title suggests, my main objective is to render a dynamic scss(.erb) file after an ajax call.
assets/javascripts/header.js
// onChange of a checkbox, a database boolean field should be toggled via AJAX
$( document ).ready(function() {
$('input[class=collection_cb]').change(function() {
// get the id of the item
var collection_id = $(this).parent().attr("data-collection-id");
// show a loading animation
$("#coll-loading").removeClass("vhidden");
// AJAX call
$.ajax({
type : 'PUT',
url : "/collections/" + collection_id + "/toggle",
success : function() {
// removal of loading animation, a bit delayed, as it would be too fast otherwise
setTimeout(function() {
$("#coll_loading").addClass("vhidden");
}, 300);
},
});
});
});
controller/collections_controller.rb
def toggle
# safety measure to check if the user changes his collection
if current_user.id == Collection.find(params[:id]).user_id
collection = Collection.find(params[:id])
# toggle the collection
collection.toggle! :auto_add_item
else
# redirect the user to error page, alert page
end
render :nothing => true
end
All worked very smooth when I solely toggled the database object.
Now I wanted to add some extra spices and change the CSS of my 50+ li's accordingly to the currently selected collections of the user.
My desired CSS looks like this, it checks li elements if they belong to the collections and give them a border color if so.
ul#list > li[data-collections~='8'][data-collections~='2']
{
border-color: #ff2900;
}
I added this to my controller to generate the []-conditions:
def toggle
# .
# .
# toggle function
# return the currently selected collection ids in the [data-collections]-format
#active_collections = ""
c_ids = current_user.collections.where(:auto_add_item => true).pluck('collections.id')
if c_ids.size != 0
c_ids.each { |id| #active_collections += "[data-collections~='#{id}']" }
end
# this is what gets retrieved
# #active_collections => [data-collections~='8'][data-collections~='2']
end
now I need a way to put those brackets in a scss file that gets generated dynamically.
I tried adding:
respond_to do |format|
format.css
end
to my controller, having the file views/collections/toggle.css.erb
ul#list<%= raw active_collections %> > li<%= raw active_collections %> {
border-color: #ff2900;
}
It didn't work, another way was rendering the css file from my controller, and then passing it to a view as described by Manuel Meurer
Did I mess up with the file names? Like using css instead of scss? Do you have any ideas how I should proceed?
Thanks for your help!
Why dynamic CSS? - reasoning
I know that this should normally happen by adding classes via JavaScript. My reasoning to why I need a dynamic css is that when the user decides to change the selected collections, he does this very concentrated. Something like 4 calls in 3 seconds, then a 5 minutes pause, then 5 calls in 4 seconds. The JavaScript would simply take too long to loop through the 50+ li's after every call.
UPDATE
As it turns out, JavaScript was very fast at handling my "long" list... Thanks y'all for pointing out the errors in my thinking!
In my opinion, the problem you've got isn't to do with CSS; it's to do with how your system works
CSS is loaded static (from the http request), which means when the page is rendered, it will not update if you change the CSS files on the server
JS is client side and is designed to interact with rendered HTML elements (through the DOM). This means that JS by its nature is dynamic, and is why we can use it with technologies like Ajax to change parts of the page
Here's where I think your problem comes in...
Your JS call is not reloading the page, which means the CSS stays static. There is currently no way to reload the CSS and have them render without refreshing (sending an HTTP request). This means that any updating you do with JS will have to include per-loaded CSS
As per the comments to your OP, you should really look at updating the classes of your list elements. If you use something like this it should work instantaneously:
$('li').addClass('new');
Hope this helps?
If I understood your feature correctly, actually all you need can be realized by JavaScript simply, no need for any hack.
Let me organize your feature at first
Given an user visiting the page
When he checks a checkbox
He will see a loading sign which implies this is an interaction with server
When the loading sign stopped
He will see the row(or 'li") he checked has a border which implies his action has been accepted by server
Then comes the solution. For readability I will simplify your loading sign code into named functions instead of real code.
$(document).ready(function() {
$('input[class=collection_cb]').change(function() {
// Use a variable to store parent of current scope for using later
var $parent = $(this).parent();
// get the id of the item
var collection_id = $parent.attr("data-collection-id");
show_loading_sign();
// AJAX call
$.ajax({
type : 'PUT',
url : "/collections/" + collection_id + "/toggle",
success : function() {
// This is the effect you need.
$parent.addClass('green_color_border');
},
error: function() {
$parent.addClass('red_color_border');
},
complete: function() {
close_loading_sign(); /*Close the sign no matter success or error*/
}
});
});
});
Let me know if my understanding of feature is correct and if this could solve the problem.
What if, when the user toggles a collection selection, you use jquery change one class on the ul and then define static styles based on that?
For example, your original markup might be:
ul#list.no_selection
li.collection8.collection2
li.collection1
And your css would have, statically:
ul.collection1 li.collection1,
ul.collection2 li.collection2,
...
ul.collection8 li.collection8 {
border-color: #ff2900;
}
So by default, there wouldn't be a border. But if the user selects collection 8, your jquery would do:
$('ul#list').addClass('collection8')
and voila, border around the li that's in collection8-- without looping over all the lis in javascript and without loading a stylesheet dynamically.
What do you think, would this work in your case?
Testing on the desktop with JQM doesn't produce this issue, so it's difficult to pinpoint.
Backstory: I have created server side code (php) to accept a query string and open a gallery straight to a picture. But if a user wants to share a link while surfing a gallery on a mobile device, and in particular a certain photo; most Mobile Browsers share the core link and not the actual photo. It's easy in the events when swiping to create a URL hashtag modifier for the URL with the photo id ( For example #photoID=987), but only if the gallery is originally started with no hashtags. It's then easy to share with a Phone's Native methods.
(function(window, $, PhotoSwipe){
$(document).ready(function(){
//More Code is here but not needed fro this question
$(photoSwipeInstance).bind(PhotoSwipe.EventTypes.onDisplayImage, function(e){
var pid = codeThatGetsPhotoIDFromDisplayedIMGURL();
window.location.hash = '&pid='+pid[0];
});
if(getUrlVars()["pid"]!=null || getUrlVars()["pid"]!=undefined)
{
console.log(getUrlVars()["pid"]);
var photopid= getPhoto(getUrlVars()["pid"]);
photoSwipeInstance.show(photopid);
}
});//End Documentstrong text
}(window, window.jQuery, window.Code.PhotoSwipe));
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
Issue: If a gallery is loaded with a hashtag the gallery will pop up the proper image but then immediately closes the slide show. And every photo past this point performs in the same manner, slideshow opens then closes.
I have turned off all AJAX, and hashtag anchor functions JQM utilizes. This hashtag url functions works as intended when using a Desktop browser but not when using any Mobile browser.
Has someone else tried this functionality?
I probably made this much more confusing then it is in my description.
Answer: JQM's hashtag handlers did not need to be turned off instead. Photoswipe needed this handler added to the options: backButtonHideEnabled: false
JQM's hashtag handlers did not need to be turned off instead. Photoswipe needed this handler added to the options: backButtonHideEnabled: false