mcmwhfy mcmwhfy - 2 months ago 7
CSS Question

if .parent() .hasclass then do not apply the function

I have this function which should be called only when parent doesn't have the class

cooling
.

function inputWidth() {
$('input[disabled="disabled"]').removeAttr("disabled").prop("readonly", true);
$('input[type!="submit"]').focus(function(){
if ($(this).val().length > 20) {
$(this).attr('data-default', $(this).width());
$(this).animate({
width: 350
}, 'slow');
$(this).parent().addClass('cooling');
}
}).blur(function(){ /* lookup the original width */
var w = $(this).attr('data-default');
$(this).animate({
width: w
}, 'fast');
$(this).parent().removeClass('cooling');
});
};

Answer

I'm thinking this is being overanalyzed. There's no reason to add an extra class to the parent (unless you're doing this for styling, in which case feel free to add it back in).

Basically we only set the default data value once, and if it's there we don't set it again (we just reuse it).

You'll also notice the use of $.data() instead of .attr(). Try to avoid .attr(). It's not all that efficient for this sort of thing as you're basically asking it to lookup or store the value in the actual DOM (manipulating the DOM is very expensive). In most cases it's not the proper usage anyways. In your code, $(this).data("default") is the proper way to get at what you want. As an example:

<input type="text" id="username" data-item="random data" />

using jQuery to get at data-item you'd call:

$("#username").data("item");

and get back "random data".

One last thing, when using animations (especially 'slow' animations) you should make it a habit to call stop first, that way any animations that are in progress are halted immediately before starting the next animation.

$('input[disabled="disabled"]').removeAttr("disabled").prop("readonly", true);
$('input').focus(function() {
    if ($(this).val().length > 20) {
        $(this).data('default', $(this).data('default') || $(this).width());
        $(this).stop().animate({
            width: 300
        }, 'slow');
    }
}).blur(function() { /* lookup the original width */
    $(this).stop().animate({
        width: $(this).data('default')
    }, 'fast');
});

Here's a jsfiddle for you as well.

I hope I've helped you, all that said, keep in mind that your original question was answered correctly by several other people on here. They all provided the correct code for not executing something if the parent has a particular class. In the future, when asking questions, please be careful to articulate exactly what issue you're having. You were asking something along the lines of "how can I toggle size based upon focus" not "if parent hasclass then do not apply...". The other answers did answer your question. The problem is you weren't asking the right question.