Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I refactor this jQuery code?

The code below is for a simple newsletter signup widget.

I'm sure there's a way to make it more concise, any ideas?

var email_form = $('.widget_subscribe form'); 
var email_submit = $('.widget_subscribe .submit');
var email_link = $('.widget_subscribe .email');

// Hide the email entry form when the page loads
email_form.hide();

// Show the form when the email link is clicked
$(email_link).click( function () {
    $(this).toggle();
    $(email_form).toggle();
    return false;
});

// Hide the form when the form submit is clicked
$(email_submit).click( function () {
    $(email_link).toggle();
    $(email_form).toggle();
});

// Clear/reset the email input on focus 
$('input[name="email"]').focus( function () {
    $(this).val("");
    }).blur( function () {
        if ($(this).val() == "") {
            $(this).val($(this)[0].defaultValue);
        }
});
like image 652
meleyal Avatar asked Dec 13 '25 20:12

meleyal


2 Answers

You have some similar code here.

// Show the form when the email link is clicked
$(email_link).click( function () {
        $(this).toggle();
        $(email_form).toggle();
        return false;
});

// Hide the form when the form submit is clicked
$(email_submit).click( function () {
        $(email_link).toggle();
        $(email_form).toggle();
});

It could be refactored so the similarity is obvious.

// Show the form when the email link is clicked
$(email_link).click( function () {
        $(email_link).toggle();
        $(email_form).toggle();
        return false;
});

// Hide the form when the form submit is clicked
$(email_submit).click( function () {
        $(email_link).toggle();
        $(email_form).toggle();
});

So you could wrap toggling the link and the form into a function.

var toggleEmailLinkAndForm = function () {
        $(email_link).toggle();
        $(email_form).toggle();
}   

$(email_link).click(toggleEmailLinkAndForm);
$(email_submit).click(toggleEmailLinkAndForm);

And as others have pointed out, you can drop the redunant $()s.

var toggleEmailLinkAndForm = function () {
        email_link.toggle();
        email_form.toggle();
}   

email_link.click(toggleEmailLinkAndForm);
email_submit.click(toggleEmailLinkAndForm);
like image 110
Patrick McElhaney Avatar answered Dec 15 '25 09:12

Patrick McElhaney


It's already pretty concise, there's not much more you can do.

Anywhere you have $(email_submit) you can just have email_submit, because you've already wrapped it in $() (which makes it a jquery object).

Eg:

email_submit.click( function () {
    email_link.toggle();
    email_form.toggle();
});
like image 22
gregmac Avatar answered Dec 15 '25 08:12

gregmac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!