So I am having an odd issue with my first rails4 app where my page javascript is not firing unless I reload the page.
This is true for both my asset pipeline JS and also inline with content_for JS.
in my /assets/javascripts/cars.js file:
$(function(){
$("#car_car_make_id").on("change", function(){
//SET MODELS
$.ajax({
url: "/car_makes/" + $(this).val() + "/car_models",
type: "GET",
dataType: "json",
cache: false
})
.done(function(data) { model_list(data) })
.fail(function() { alert("error"); })
});
});
function model_list(data) {
$("#car_car_model_id").empty();
$.each(data, function(i,v){
$("<option />").val(v.id).text(v.name).appendTo("#car_car_model_id");
});
//ON COMPLETE SHOW
$("#car_model_div").show();
}
inline in page with content_for:
<% content_for :head do %>
<script type="text/javascript">
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('yt_vid', {
height: '390',
width: '640',
videoId: '<%= @timeslip.youtube_id %>'
});
}
</script>
<% end %>
Both of these only fire if i refresh the page.
For example, if i click a link to the page with the youtube video it will not load. but if I refresh it will. Same with the asset pipeline script, it only makes my ajax call if i reload the page first.
looks like a side effect of the new Turbolinks feature. When you click a link, the page isn't being reloaded -- it's just having its <body>
loaded by an AJAX request. So:
In the first case, the $(function{ ... })
isn't being run because document.ready
is only fired on the first page load, not reloading the body.
In the second case, the <head>
isn't reloaded with turbolinks, just the body. So you're left with the old <script>
and it isn't rerun!
Check some of the options for turbolinks, like jquery.tubrolinks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With