Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I DRY up these jQuery calls?

Is there a way to DRY this jQuery up?

<script type="text/javascript">
  $('form input#search').watermark('search...');
</script>
<script type="text/javascript">
  $('form input#post_title').watermark('title');
</script>
<script type="text/javascript">
  $('form input#post_tag_list').watermark('tag (separate tags with a comma)');
</script>
<script type="text/javascript">
  $('form input#post_name').watermark('name (optional)');
</script>
<script type="text/javascript">
  $('form input#post_email').watermark('email (optional)');
</script>
<script type="text/javascript">
  $('form textarea#post_content').watermark('message');
</script>
<script type="text/javascript">
  $('form input#comment_commenter').watermark('name (optional)');
</script>
<script type="text/javascript">
  $('form input#comment_email').watermark('email (optional)');
</script>
<script type="text/javascript">
  $('form textarea#comment_body').watermark('reply');
</script>
<script type="text/javascript">
  jQuery(document).ready(function() {
    jQuery("abbr.timeago").timeago();
  });
</script>

It seems awfully repetitive.

EDIT: I added placeholder elements to all my forms. My app is HTML5 so it's okay. I used this code:

<script type="text/javascript">
  jQuery(function(){
    jQuery("abbr.timeago").timeago();
    jQuery('form input, form textarea').each(
      function(){
        jThis = jQuery(this);
        jThis.watermark(jThis.attr('placeholder'));
      }
    }
  );
</script>

Chrome renders the placeholders with or without JS, while FF 3.6.8 and Opera 10.61 show empty input/textarea boxes. Should I be using $ instead of jQuery(function(){... ? Or does it matter?

note: I'm using jQuery 1.4.2

like image 960
66tree Avatar asked Dec 22 '22 00:12

66tree


1 Answers

If you stored the parameter for the watermark function in the title attributes then you could have something like this;

<form>
    <input type="text" id="search" title="search..." />
    <input type="text" id="post_title" title="title" />
    <input type="text" id="post_tag_list" title="tag (separate tags with a comma)" />
    <input type="text" id="post_name" title="name (optional)" />
    <input type="text" id="post_email" title="email (optional)" />
    <input type="text" id="post_content" title="message" />
    <input type="text" id="comment_commenter" title="name (optional)" />
    <input type="text" id="comment_email" title="email (optional)" />
    <input type="text" id="comment_body" title="reply" />
</form>

<script type="text/javascript">
    jQuery(function(){
        jQuery("abbr.timeago").timeago();
        jQuery('form input, form textarea').each(
            function(){
                jThis = jQuery(this);
                jThis.watermark(jThis.attr('title'));
            }
        }
    );
</script>
like image 190
Simon Avatar answered Jan 13 '23 15:01

Simon