Question

I'm learning / trying to be better in jQuery. I was wondering if the following is acceptable markup, or is there a cleaner, smaller way to accomplish the same?

$(document).ready(function(){
    $('#searchwrapper .searchbox').focus(function(e) {
            $('#searchwrapper .searchbox_submit').css('color', '#999999'); 
        }
    );
    $('#searchwrapper .searchbox').focusout(function(e) {
            $('#searchwrapper .searchbox_submit').css('color', '#dddddd'); 
        }
    );
});

EDIT / SOLUTION

Thanks to Arun P Johny and senyor Toni the js I ended up using.

$(document).ready(function(){
    var swap_color = $('#searchwrapper .searchbox_submit');
    $('#searchwrapper .searchbox').focus(function(e) {
            swap_color.css('color', '#999999'); 
        }
    ).blur(function(e) {
            swap_color.css('color', '#dddddd'); 
        }
    );
});
Was it helpful?

Solution

It looks ok, probably you can improve the usage of selectors by caching it.

  1. Chain the event handlers
  2. Cache the selector $('#searchwrapper .searchbox_submit') using a variable

Try

$(document).ready(function(){
    var searchbox_submit = $('#searchwrapper .searchbox_submit');
    $('#searchwrapper .searchbox').focus(function(e) {
            searchbox_submit.css('color', '#999999'); 
        }
    ).focusout(function(e) {
            searchbox_submit.css('color', '#dddddd'); 
        }
    );
});

OTHER TIPS

You can chain to make a more optimized jquery sentence, and use blur instead of focusout since this one bubbles the focus out event and you probably don't need event bubbling, like that:

$('#searchwrapper .searchbox').focus(function(e) {
        $('#searchwrapper .searchbox_submit').css('color', '#999999'); 
    }
).blur(function(e) {
        $('#searchwrapper .searchbox_submit').css('color', '#dddddd'); 
    }
);

Also you should store the jquery selectors that will be used in the future in a javascript variable, like this:

var selector = $('#searchwrapper .searchbox_submit');

then call css:

$('#searchwrapper .searchbox').focus(function(e) {
        selector.css('color', '#999999'); 
    }
).blur(function(e) {
        selector.css('color', '#dddddd'); 
    }
);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top