Skip to content


OnClick Rails Helper for Disqus Style Input Fields

If you haven’t seen comments by Disqus, you should probably check them out. If you don’t care about having programmatic access (as of this post) then its the simplest way of adding a comment system to your website. While their comment widget is pretty neat, i wanted to have the same effects on my input fields that they use, but with all the control and “flexibility” that rails gives me.

I wanted an input that had the default text grayed out, when you click on it and start typing your text becomes black, and if you delete your text and click outside of the area, the input goes back to its default value. And back to gray. To accomplish this task, i wrote my own custom helper /app/helpers/application_helper.rb:

def default_text_field(name, value)

text_field(name, :value => value,  :class => "gray-input", :onfocus => "if (this.value=='#{value}') this.value = '';this.style.color = 'black';", :onblur => "if (this.value=='') {this.value = '#{value}';this.style.color = '';}" )

end

So now when i use it in a view like this:

<%= f.default_text_field :website, "Example.com" %>

My view acts like this:

onClickrailsHelper

The CSS needed for this to work properly is extremely simple:

.gray-input {
color: #7a7a7a;
}

Of course you can use another color if you wish. Hope you enjoyed this little tip, and I hope all your users fall all over themselves at the awesomeness of your sweet new inputs. Good luck, and happy coding.

Posted in Austin, Musings, Ruby On Rails, Web Development. Tagged with , , , , , , .

0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

Some HTML is OK

(required)

(required, but never shared)

or, reply to this post via trackback.