1

I want to know if there's a way to make this code more efficient please, I am trying to improve my own code but I feel I need feedback, with this part:

$(function(){
    $('#buscar').focus(function(){
        if(($(this).val() === '') || ($(this).val() === ' ') || ($(this).val() === 'Buscar...'))
            $(this).val('');
    }).change(function(){
        if(($(this).val() === '') || ($(this).val() === ' ') || ($(this).val() === 'Buscar...'))
            $(this).css({'color':'#999999'});
        else
            $(this).css({'color':'#000000'});
    }).blur(function(){
        if(($(this).val() === '') || ($(this).val() === ' '))
           $(this).val('Buscar...');
    });
});
8
  • what are you trying to optimize here? Commented Dec 20, 2010 at 7:30
  • not repeat that many times the same if statement, I do that a lot in all of my code =/ Commented Dec 20, 2010 at 7:32
  • 2
    Am I gathering correctly that you're trying to implement a placeholder/watermark script for a search field? Why are you checking for === ' ', what's so special about a single space? Commented Dec 20, 2010 at 7:33
  • yes I am =), I am truly impressed by you noticing it haha. // I've had trouble when people send a single space that's why if they leave it empty I just fill it with the default again Commented Dec 20, 2010 at 7:34
  • touché @deceze - do you speak spanish? Commented Dec 20, 2010 at 7:37

7 Answers 7

1
/* ==========================================================
 * speed and readable improvment
 * ========================================================== */
$(function(){
    $('#buscar')
      .bind('focus change blur', function(){
          var $this = $(this);
          if(event.type === 'focus' || event.type === 'change')
            $this
              .iff($this.isEdited('Buscar...'))
                .val('')
                .end();
          else if(event.type === 'blur')
            $this
              .iff($this.isEdited(null))
                .val('Buscar...')
                .end();
      });
});

(function($){
  '$:nomunge'; // Used by YUI compressor.

  $.fn.iff = function( test ) {
    var elems = !test || $.isFunction( test )
      && !test.apply( this, Array.prototype.slice.call(arguments, 1) )
      ? []
      : this;
    return this.pushStack( elems, 'iff', test );
  };

})(jQuery);

$.fn.isEdited = function(placeholder) {
    if(typeof placeholder !== 'string')
      placeholder = '';

    var val = $(this).val();
    return $.trim(val) === '' || val === placeholder;
};

Edited: rewrite the code to add the idear from 'Mohan Ram' (multiple event binding) Remark: you can use this code also without the "iif"-extension if you like. then you must write:

if((event.type === 'focus' || event.type === 'change') && $this.isEdited('Buscar...'))
Sign up to request clarification or add additional context in comments.

Comments

1

I think this is the simplest way to write your code in optimised way

$(function(){
    $('#buscar').bind('focus change blur' , function(){
  //write ur codes here
});

1 Comment

+1 very good idear. i have change my answer to reflect this and show a sample stackoverflow.com/questions/4487662/…
0

Having the extra knowledge, thanks to @deceze's insight, I would recommend factoring out most of this logic into a single function. Essentially all these conditions are checking if the field is empty or not.

Also, I am adding a check for any sort of whitespace since a single " " is just as irrelevant as two spaces " ".

function isTextFieldEmpty(text, placeholder) {
    var onlyWhitespace = /^\s+$/;
    return (text == "" || onlyWhitespace.test(text) || text == placeholder);
}

Then you can reuse this function for all the events - focus, blur, change.

$(function() {

    // to avoid repeating this text everywhere..
    var placeholder = 'Buscar...';

    $('#buscar').focus(function() {
        if (isTextFieldEmpty(this.value, placeholder)) {
            $(this).val('');
        }
    });

    $('#buscar').blur(function() {
        if (isTextFieldEmpty(this.value, placeholder)) {
            $(this).val(placeholder);
        }
    });

    $('#buscar').change(function() {
        if (isTextFieldEmpty(this.value, placeholder)) {
            $(this).css({ color: '#999' });
        }
        else {
            $(this).css({ color: '#000' });
        }
    });

});

Comments

0

I would go for something like the code below. It isolates the functions you need (test for empty string, or test for no value or the placeholder text). Also, I don't believe the change function is the right place to change the color; rather it should be in the focus and blur functions where you also change the value.

Also, if you are simply looking for a placeholder method for an input field, there are many already made for you, where you set the text and the CSS style. Also, HTML 5 has a placeholder attribute for this purpose - see http://davidwalsh.name/html5-placeholder. Some of the better placeholder plugins even use HTML 5 and fall back on JS if it is not supported.

Anyway, here is the code:

$.fn.isValBlank = function() {
    return $.trim($(this).val()) == "";
};

$.fn.isInputBlank = function() {
    return (($(this).isValBlank() || ($(this).val() === 'Buscar...'));
};

$(function(){
    $('#buscar').focus(function(){
        var val = $(this).val();
        if ($(this).isInputBlank()) {
            $(this).val('');
            $(this).css({'color':'#000'});
        }
    });

    $('#buscar').blur(function(){
        if ($(this).isValBlank()) {
            $(this).css({'color':'#999'});
            $(this).val('Buscar...');
        }
    });
});

Comments

0

If it were the future and HTML5 were everywhere, or if everybody used only current versions of Safari, Chrome, and Firefox, then you could knock out most of that code and replace it with this:

<input name="something" id="buscar" placeholder="Buscar...">

But since, as of this writing, it's still the present, you can tighten things up a little like this:

function isEdited(el,placeholder){
  placeholder = typeof placeholder == 'undefined' ? 'Buscar...' : placeholder;
  return $.trim( $(el).val() ) === placeholder;
}

$('#buscar').focus(function(){
  if( isEdited(this) )
      $(this).val('');
}).change(function(){
  if( isEdited(this) )
      $(this).css({'color':'#999999'});
  else
      $(this).css({'color':'#000000'});
}).blur(function(){
    if( $.trim( $(this).val() ) )
       $(this).val('Buscar...');
});

If you need to do a lot of this, you might consider the jQuery Placeholder Plug-in. It uses the placeholder attribute, so it's HTML5-friendly.

Also,

Comments

0

HTML input elements have a defaultValue property accessible by JavaScript. When talking about placeholder text input values, you can use this to help make code more reusable. This isn't perfect by any means but...

$(function(){

    $("input[type='text']").focus(textInputFocusHandler).change(textInputChangeHandler).blur(textInputBlurHandler);

});

function hasUserValue(textInput) {
    return (textInput.value!=textInput.defaultValue && /^\s+$/.test(textInput.value)==false && textInput.value!=="");
}

function textInputFocusHandler(event) {
    if(!hasUserValue(event.target)) event.target.value = "";
}

function textInputChangeHandler(event) {
    if(!hasUserValue(event.target)) event.target.style.color = "#999";
    else event.target.style.color = "#000";
}

function textInputBlurHandler(event) {
    if(!hasUserValue(event.target)) event.target.value = event.target.defaultValue;
}

Comments

0

Quick optimization:

$(function(){
$('#buscar').focus(function(){
    var t = $(this);
        var v = $.trim(t.val());
 if(v === '' || 'Buscar...'){
    $(this).val('');
        }
}).change(function(){
    var t = $(this);
        var v = $.trim(t.val());
 (v === '' || 'Buscar...' ? t.css({'color':'#999999'}) : t.css({'color':'#000000'}))
}).blur(function(){
    var t = $(this);
        var v = $.trim(t.val());
    if(v === '')
       t.val('Buscar...');
});
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.