Jronny
Jronny

Reputation: 2284

Optimize jquery code

$(textBox).focus( function() {
    $(spans).css({"background-position": "0 100%"});
});
$(textBox).blur( function() {
    $(spans).css({"background-position": "0 0"});
});

This is already short but it's either I am just too paranoid, or we could code this shorter by

$(textBox).bind('focus blur', function() { *do toggle here* }); 

or something else.

Any help would be greatly appreciated. =)

Upvotes: 1

Views: 235

Answers (5)

jerjer
jerjer

Reputation: 8760

You can try this as well:

$(textBox).bind('focus blur', function(e) {
    var bg = (e.type=='blur') ? '0 0' : '0 100%';
    $(spans).css({"background-position": bg});

});

Upvotes: 3

jitter
jitter

Reputation: 54605

$("#test").bind("focus blur", function (e) {
    $(spans).css({"background-position": e.type === "focus" ? "0 100%" : "0 0"});
});

Upvotes: 1

Guffa
Guffa

Reputation: 700212

If you want to use the same function for both the events, you need to use a way of changing the effect that can be used to turn it both ways. Something like:

$(textBox).bind('focus blur', function() { $(spans).toggleClass('over'); });

If there are a lot of elements that you want to change the effect on, you should consider using the cascading effect of CSS instead of letting jQuery change the class for all the elements, i.e. changing the class for a single parent element, and have a style that targets all the child elements that you want to affect:

#container span { background-position: 0 0; }
#container.over span { background-position: 0 100%; }

Changing the class of the parent will change the style of all affected children:

$(textBox).bind('focus blur', function() { $('#container').toggleClass('over'); });

Upvotes: 2

Dave Archer
Dave Archer

Reputation: 3060

I think there's a line between optimization and code clarity. Without any further evidence, I don't believe you'll see any major improvements as far as optimizations go.

Keeping these two separate allows for a very quick and easy scan... No logic to go through. Its just "When this happens, then do this". Simple and you're probably losing, if anything, very little.

Edit: If like you mentioned in a comment you want to toggle the class, you could

$(textBox).bind('focus blur', function() { 
var currentClass = $(this).attr('class');
var newClass = currentClass == 'gotFocus' ? 'noFocus' : 'gotFocus';
$(this).removeClass(currentClass).addClass(newClass); });

Upvotes: 2

Jacob Relkin
Jacob Relkin

Reputation: 163228

Try this:

$( textBox ).focus( function(){...} ).blur( function() {...} );

And yes, you can also use the bind() function as you specified.

I find my version more readable.

Good luck!

Upvotes: 5

Related Questions