I generally learn more by doing something rather than just reading about it, or watching someone else do something. I’ve been working through each of the exercises in the Ruby on Rails tutorial with the hope that some of this knowledge will sink in. I’ve now reached the exercises for the penultimate :) chapter of the tutorial, and the last exercise for this chapter is prefaced with the warning challenging:
Simple enough, I imagine. We’ll just display the number of remaining characters below the text field like so:
The first thing we’ll do is add a div to the existing partial for the home page that I’ll call “counter” (line 6):
Unfortunately this places the counter in an awkward location:
So to fix this, we’ll add a class “counter” to the div:
And add a “counter” class definition to the custom.css.scss file in the microposts section:
Now the counter will be displayed in the lower right corner as shown in the first example.
So what’s going on here?
 Wait for the document to load using $(document).ready().
 Bind our handler method to the keyup event for the micropost_content textarea element.
$("#micropost_content") returns the element having an id matching micropost_content. keyup() binds the specified function to the keyup event.
 Set the text of the counter div element to the difference of 140 and the length of the text in the micropost_content element. $this refers to the micropost_content textarea element.
To give this counter added emphasis, it would be nice to set the color of the text to red when the value becomes negative.
Points of interest:
 The counter variable was added so that we don’t need to traverse the DOM again to get the micropost_content element.
 The value of the variable charsRemaining will be displayed in the counter div and will also be used to determine the text color.
 Here the jQuery css() method is used to set the value of the ‘color’ property of the counter element. The ternary operator is employed to return the text color, reads as “If charsRemaining is less than zero, return ‘red’ otherwise return ‘black’”. The string returned is passed as an argument to the css() method to set the ‘color’ property. Now when the maximum number of characters is exceeded the text should be red:
Although I could probably leave the script tag in the micropost form partial, I’d rather like to have it pulled into the head element of the document. I came across one suggestion for how to do this on StackOverflow. First, wrap the script section in a content_for block, like so:
Then yield to the block in the application layout (line 8):
If you view source on the home page now you should see that the counter script appears in the head element. Furthermore, when you browse to any other page, the counter script shouldn’t exist.
Leave a Comment
Your email address will not be published. Required fields are marked *