Search code examples
jqueryfocussemantic-markupfocusout

jquery focus and focusout, is this considered acceptable markup?


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'); 
        }
    );
});

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'); 
            }
        );
    });