0

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.

1 Answer 1

2

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 () { /* ... */ });
Sign up to request clarification or add additional context in comments.

1 Comment

Yup I ended up using jquery-turbolinks ready callback. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.