14

This is the piece of jQuery I wrote,

$('#editUser').click(function() {
    if ($(".selectedTR")[0]) {
        if($('.form-actions').is(':visible')) {
            $('.form-actions').slideUp('slow',function() {
                $('.form-actions > h3').text("Edit");
            }).css('display', 'none');
        }

        $('.form-actions').css('display', 'block').slideDown('slow');
    } else {
        alert("Please select a user");
    }
});

How can I remove the duplicated selectors?

7
  • 6
    declare a variable for $('.form-actions') and use it.
    – vcsjones
    Commented Dec 4, 2012 at 14:59
  • PHPStorm WTF. I'm getting tired of constantly telling people to cache their queries. Commented Dec 4, 2012 at 15:02
  • @ŠimeVidas huh ? Its good phpstorm is highlighting inefficeint code, isn't it ? Commented Dec 4, 2012 at 15:11
  • @NimChimpsky LOL, I meant FTW, not WTF. Commented Dec 4, 2012 at 15:14
  • codereview.stackexchange.com might be better suited for this sort of question, since there's nothing actually broken in your code. Commented Dec 4, 2012 at 15:14

1 Answer 1

27

You can cache the selector by putting it in a variable. Try this:

$('#editUser').click(function() {
    if ($(".selectedTR").length) { 
        var $formActions = $('.form-actions');
        if ($formActions.is(':visible')) {
            $formActions.slideUp('slow', function() {
                $formActions.children('h3').text("Edit");
            }).css('display', 'none');
        }
        $formActions.css('display', 'block').slideDown('slow');
    } else {
        alert("Please select a user");
    }
});
1
  • 7
    You could even replace if ($formActions.is(':visible')) { $formActions.slideUp( with $formActions.filter(':visible').slideUp( Commented Dec 4, 2012 at 15:19

Not the answer you're looking for? Browse other questions tagged or ask your own question.