Reputation: 435
I'm working on a web application using rails. I have individual html.erb
files where I run script.js
on each file. I want to follow DRY so I want to put script.js
in my layout's file instead of each individual view file.
Here is script.js
:
if(document.documentElement.clientWidth < 570) {
//do some stuff
}
This works fine when I put it in each of my view individually but doesn't work when I only put it in my layouts file. I have a feeling that this is because I am using document
. If this is true I'm not sure what I should replace document
with. If this is not true then I'm not sure what is wrong.
If you could help me understand why script.js
doesn't work when I put it in the layouts file that would be greatly appreciated.
Upvotes: 0
Views: 40
Reputation: 1746
What you can do:
Put you files in:
lib/assets/javascript
or put your file in
vendors/assets/javascript
After that load the file in application.js
//=require script.js
In script.js, you can add conditions if you want to run the script only for few pages. You can check for example if a div exists into your html page
if ($('#mydiv').length){
//do something
}
If you are using turbolinks, the situation will change, you will need to do more things: You can install jquery-turbolinks and have your methods in a function
$(document).ready(function () { /* ... */ });
Upvotes: 2