ugrás a tartalomhoz

Adding HTML5 placeholder attribute support through progressive enhancement

Joó Ádám · 2010. Jún. 23. (Sze), 09.42
Hogyan vegyük használatba a placeholder attribútumot
 
1

jQuery plugin

Poetro · 2010. Jún. 23. (Sze), 18.42
Erre én írtam egy valamivel szebben konfigurálható jQuery plugint:
(function ($) {
  $.fn.extend({
    /**
     * Placeholders for input elements which hide on focus.
     *
     * Uses the current value as the placeholder,
     * unless overriden by `useAttribute`.
     *
     * Usage:
     *  $('input').inputPlaceholder({
     *    'blurClass' : 'field-blur',
     *    'focusClass' : 'field-focus',
     *    'clearOnSubmit' : true,
     *    'useAttribute: 'title'
     *  });
     *
     * @param settings Object
     *   Set the following behaviors:
     *    - `blurClass` : class to be added to the field on blur (default is '').
     *    - `focusClass` : class to be added to the field on focus (default is '').
     *    - `clearOnSubmit` : clear the field value, if contains default value.
     *    - `useAttribute` : use an attribute of the field, instead of the
     *                       current value for the placeholder (default is false).
     * @returns jQuery object of the original selection for chaining.
     */
    inputPlaceholder : function (settings) {
        // Only use the INPUT type TEXT and PASSWORD
        var inputs = $(this).filter(':text, :password');

        // Focus and blur classes.
        settings = $.extend({
            'blurClass'    : '',
            'focusClass'   : '',
            'clearOnSubmit': false,
            'useAttribute' : false
          }, settings);

        if (inputs.length) {
          inputs.each(function () {
            var $this = $(this),
                placeholder = settings.useAttribute ?
                  this[useAttribute] || '' :
                  $this.val();

            $this.bind('focus.inputPlaceholder blur.inputPlaceholder', function(event) {
                // Store current value, to be used later on.
                var fieldValue = $this.val();

                switch (event.type) {
                  case 'focus':
                    // Field's value is the same as the default, so make it empty
                    if (placeholder === fieldValue) {
                      $this.val('').removeClass(settings.blurClass).addClass(settings.focusClass);
                    }
                    break;

                  case 'blur':
                    // Field value is empty so fill it with default.
                    if (fieldValue === '') {
                      $this.val(placeholder).removeClass(settings.focusClass).addClass(settings.blurClass);
                    }
                    break;
                }
              });

          }).addClass(settings.blurClass);

          // Should it clear the default value on submit?
          if (settings.clearOnSubmit) {
            inputs.parents('form:first')
              .bind('submit.inputPlaceholder', function () {
                inputs.each(function () {
                  // Have to go through each,
                  // as triggerHandler only triggers for first item
                  $(this).triggerHandler('focus.inputPlaceholder');
                })
              });
          }
        }

        return this;
      }
  });
}(jQuery));
És ezután csak
if (!('placeholder' in document.createElement('input'))) {
  $('input:text[placeholder]').inputPlaceholder({'useAttribute': 'placeholder'});
}
2

Nagyon tetszik

N0r3i · 2010. Jún. 27. (V), 12.18
Szia!

Pont ilyesmit keresgéltem a saját, kicsit béna megoldásom helyett.

Egy kis baki van azért benne: a 43. sorban a this helyett $this kell, gondolom csak elírás... Így már tökéletesen működik, köszönöm!

Norbi
3

Javított változat

Poetro · 2010. Jún. 27. (V), 17.08
Enyhén optimalizált, rövidebb javított változat:
(function ($) {  
  $.fn.extend({  
    /**
     * Placeholders for input elements which hide on focus.
     *
     * Uses the current value as the placeholder,
     * unless overriden by `useAttribute`.
     *
     * Usage:
     *  $('input').inputPlaceholder({
     *    'blurClass' : 'field-blur',
     *    'focusClass' : 'field-focus',
     *    'clearOnSubmit' : true,
     *    'useAttribute: 'title'
     *  });
     *
     * @param settings Object
     *   Set the following behaviors:
     *    - `blurClass` : class to be added to the field on blur (default is '').
     *    - `focusClass` : class to be added to the field on focus (default is '').
     *    - `clearOnSubmit` : clear the field value, if contains default value.
     *    - `useAttribute` : use an attribute of the field, instead of the
     *                       current value for the placeholder (default is false).
     * @returns jQuery object of the original selection for chaining.
     */
    inputPlaceholder : function (settings) {
      // Only use the INPUT type TEXT and PASSWORD
      var inputs = $(this).filter('input:text, input:password'),
          focus = 'focus.inputPlaceholder',
          blur = 'blur.inputPlaceholder',
          clearValues;

      // Focus and blur classes.
      settings = $.extend({
          'blurClass'    : '',
          'focusClass'   : '',
          'clearOnSubmit': false,
          'useAttribute' : false
        }, settings);

      if (inputs.length) {
        inputs.each(function () {
          var field = $(this),
              placeholder = settings.useAttribute ?
                field.attr(settings.useAttribute) :
                field.val();

          field.bind(focus, function(event) {
              // Store current value, to be used later on.
              var fieldValue = field.val();

              // Field's value is the same as the default, so make it empty
              if (placeholder === fieldValue) {
                field.val('').removeClass(settings.blurClass).addClass(settings.focusClass);
              }
            }).bind(blur, function () {
              // Store current value, to be used later on.
              var fieldValue = field.val();

              // Field value is empty so fill it with default.
              if (!fieldValue) {
                field.val(placeholder).removeClass(settings.focusClass).addClass(settings.blurClass);
              }
            }).triggerHandler(blur);
        });

        // Should it clear the default value on submit?
        if (settings.clearOnSubmit) {
          clearValues = function () {
            inputs.each(function () {
              // Have to go through each,
              // as triggerHandler only triggers for first item
              $(this).triggerHandler(focus);
            });
          };
          inputs.parents('form:first').bind('submit.inputPlaceholder', clearValues);
          $(window).bind('unload.inputPlaceholder', clearValues);
        }
      }

      return this;
    }
  });  
}(jQuery));