I have a posts.js
file that looks like this:
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');
}
});
};
var counter = function(event) {
var fieldValue = $(this).val();
var wc = fieldValue.trim().replace(regex, ' ').split(' ').length;
var regex = /\s+/gi;
var $wcField;
var maxWc;
if ($(this)[0] === $('#post_title')[0]) {
$wcField = $('#wordCountTitle');
maxWc = 7;
} else {
$wcField = $('#wordCountBody');
maxWc = 150;
}
$wcField.html(wc);
$wcField.toggleClass('over-limit', wc > maxWc);
};
$(document).ready(ready);
$(document).on('ready page:load', function () {
$('#post_title, #body-field').on('change keyup paste', counter);
});
In my application.html.erb
page, I have this:
<div id="secondary" class="col-sm-3 sidebar" style="display: none;">
<aside>
<div class="about">
<h4>Submit Report</h4>
<%= render "posts/form" %>
</div>
</aside>
</div> <!-- /#secondary -->
And when I toggle this div, and the _form
partial is displayed, the JS works fine in those fields.
But if I go to posts/new
or /posts/:id/edit
, it doesn't.
Even though if I check the source of that page, I see the post.js
included there.
What could be causing this?
Edit 1
I am using Turbolinks, if that matters.
Edit 2
I tried this, per suggestions in the Answers:
var ready;
ready = function() {
// This is the Sidebar toggle functionality
var toggleSidebar = $(".togglesidebar");
var primary = $("#primary");
var secondary = $("#secondary");
$(document).on("click", ".togglesidebar", 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');
}
});
};
But that hasn't worked.
The key issue I am having a problem with is the 'counters', i.e. #wordCountTitle
and #wordCountBody
don't work on my /posts/new
even though they work on the posts/index
when .toggleSidebar
is activated.
//= require_tree .
in myapplication.js
. That should cover everything in my JS directory no?$(document).on('page:load', ready);
after$(document).ready(ready);