So I have a button that I press that executes some JS. But what is happening is on the first load of the page it works, but once I go to another page and press the button on that new page, it doesn't work.
Per the Turbolinks documentation, this is normal - so I have to make a modification.
This was partially covered in this RailsCast - http://railscasts.com/episodes/390-turbolinks?view=asciicast - but the solution that Ryan gives is in CoffeeScript and I am using plain old vanilla JS.
This is my posts.js
file:
$(function(){
var toggleSidebar = $("#togglesidebar");
var primary = $("#primary");
var secondary = $("#secondary");
toggleSidebar.on("click", function(){
if(primary.hasClass("col-sm-9")){
primary.removeClass("col-sm-9");
primary.addClass("col-sm-12");
secondary.css('display', 'none');
}
else {
primary.removeClass("col-sm-12");
primary.addClass("col-sm-9");
secondary.css('display', 'inline-block');
}
});
});
$(document).on('page:load');
Per RailsCasts, this is what they suggest:
ready = ->
$('.edit_task input[type=checkbox]').click ->
$(this).parent('form').submit()
$(document).ready(ready)
$(document).on('page:load', ready)
When I try this at the bottom of my posts.js
:
$(document).ready();
$(document).on('page:load', ready());
I get this error:
Uncaught ReferenceError: ready is not defined
Thoughts on how I can get this? I am pretty sure it is simple, but I have very little JS experience and even less with CoffeeScript.
If you're using JS, not CoffeeScript, why you have ready = ->
in your JS file?
Try this.
var ready;
ready = function() {
$('.edit_task input[type=checkbox]').click(function() {
$(this).parent('form').submit();
});
};
$(document).ready(ready);
$(document).on('page:load', ready);
In your case:
var ready;
ready = function() {
var toggleSidebar = $("#togglesidebar");
var primary = $("#primary");
var secondary = $("#secondary");
toggleSidebar.on("click", function(){
if(primary.hasClass("col-sm-9")){
primary.removeClass("col-sm-9");
primary.addClass("col-sm-12");
secondary.css('display', 'none');
}
else {
primary.removeClass("col-sm-12");
primary.addClass("col-sm-9");
secondary.css('display', 'inline-block');
}
});
};
$(document).ready(ready);
$(document).on('page:load', ready);