I'm using Barrating Javascript from https://antennaio.github.io/jquery-bar-rating/ on my Rails application which uses Turbolinks for the page loads.
I've included the barrating.min.js in my javascripts and i'm loading it in my application.js using //=require - it all loads in fine.
I then have a ratings.js located in my assets/javascripts area that makes the call to create the jquery bar on the page.
document.addEventListener("turbolinks:load", function(event) {
console.log('page is fully loaded');
//$('#user_track_rating_drums').barrating("destroy");
$('#user_track_rating_drums').barrating({
theme: 'bars-horizontal',
reverse: true,
initialRating: 1,
onSelect: function(value, text, event) {
if (typeof(event) !== 'undefined') {
if (value >= 8) {
document.getElementById('average_drums_class').className = 'green';
}
else if (value >= 6) {
document.getElementById('average_drums_class').className = 'yellow';
}
else if (value >= 3) {
document.getElementById('average_drums_class').className = 'orange';
}
else {
document.getElementById('average_drums_class').className = 'red';
}
// rating was selected by a user
console.log(event.target);
} else {
// rating was selected programmatically
// by calling `set` method
}
}
});
})
Everything works fine on the first page load / or if it manually refresh the page, but if it navigate from the page - which uses Turbolinks, when i come back instead of the bars creating again i get a Uncaught TypeError: $(...).barrating is not a function.
I've tried calling the barrating function from the console to attach it to something else on the page but it's not found.
Checked the page and the barrating.min.js is still included in the HEAD.
I tried destroying it before creating it again but no luck. I think its an issue with the page loading with turbolinks
So managed to figure it out finally after some trial and error.
I removed the code to call and attach the barrating from the assets/javascripts area and placed it inline directly on the page required.
It now triggers without errors on first and subsequent loads.
Not entirely sure what the problem is with having it in the assets area but this resolves it