This tutorial aims to guide you on how to integrate JavaScript and CSS into a Rails application. By the end of this tutorial, you should be able to add dynamic behaviour and style to your Rails web pages using JavaScript and CSS.
Basic understanding of Rails, CSS, and JavaScript.
Rails uses the Asset Pipeline to handle JavaScript and CSS. The Asset Pipeline compiles, minifies, and compresses assets (JavaScript and CSS) to improve the speed and reduce the load time of your application.
.js
file in the app/assets/javascripts
directory.javascript_include_tag
.<%= javascript_include_tag 'example' %>
.css
file in the app/assets/stylesheets
directory.stylesheet_link_tag
.<%= stylesheet_link_tag 'example' %>
example.js:
// This is a simple function to hide an element
function hideElement(id) {
var element = document.getElementById(id);
element.style.display = 'none';
}
application.html.erb:
<%= javascript_include_tag 'example' %>
<div id="myElement">Hello, World!</div>
<button onclick="hideElement('myElement')">Hide</button>
When you click the "Hide" button, the "Hello, World!" message will disappear.
example.css:
/* This is a simple style to change the color of a text */
.text-red {
color: red;
}
application.html.erb:
<%= stylesheet_link_tag 'example' %>
<div class="text-red">Hello, World!</div>
The "Hello, World!" text will be displayed in red.
In this tutorial, you learned how to integrate JavaScript and CSS into Rails using the Asset Pipeline. You now know how to add dynamic behaviour and style to your Rails web pages.
For further learning, explore more complex JavaScript and CSS integration scenarios, such as using JavaScript libraries (like jQuery) or CSS frameworks (like Bootstrap).
JavaScript:
function changeColor(id) {
var element = document.getElementById(id);
element.style.color = 'blue';
}
CSS:
.bold-underlined {
font-weight: bold;
text-decoration: underline;
}
Rails:
<%= javascript_include_tag 'example' %>
<%= stylesheet_link_tag 'example' %>
<div id="myElement" class="bold-underlined">Hello, World!</div>
<button onclick="changeColor('myElement')">Change Color</button>
The "Hello, World!" text will be bold, underlined, and its color will change to blue when the button is clicked.