JavaScript code can access and manipulate the browser's DOM tree Show archive.org snapshot . Using JavaScript we can add interactive behavior to our interfaces that would not be possible through declarative rules in HTML and CSS alone.
Know how to use the native DOM API to do the following:
In your MovieDB, in the movies list, add a button that says "Count movies".
Once the user clicks on that button, a piece of JavaScript will count the movies in the list above and replace the button text with the number of movies counted.
Tip
We want to avoid mixing HTML, JavaScript and CSS within the same file. Therefore, don't embed your JavaScript into your view. Instead, put your JavaScript code into a
.js
file that is loaded by your layout.Note that if you load your JavaScript from your
<head>
the DOM may not be parsed yet. You will need to delay your JavaScript until theDOMContentLoaded
Show archive.org snapshot event.
In your MovieDB, write a CSS class that highlights a row in a list of records, e.g. in the index
action of the movies
resource.
Write some JavaScript that automatically applies that CSS class when the user's mouse hovers over a row. When the mouse pointer exits the element box, the CSS class is removed automaticallly.
Note
In a real application we would achieve this effect with a simple CSS rule.
Your application will eventually have a lot of JavaScripts. Putting them all into a single, giant JavaScript file is not sustainable. Instead, you should have a single short .js
file for each component or concern.
For instance, it could look like this:
app/
assets/
application.js
application/
components/
count_items.js
highlight_rows.js
The component files are loaded from application.js
.
Tip
Entrypoints are JavaScript files that can be loaded individually from your application layout. By default your Rails application has a single entrypoint
application.js
, which shouldimport
all other files.A case for multiple entrypoints would be an application that has two areas with a distinct look and feel. For instance there is (1) a visually ambitious frontend for consumers and (2) an admin area that has tightly packed data grids. Both areas would not share any CSS or JavaScript, so we would have two separate entrypoints.