user1381806
user1381806

Reputation: 529

Optimize JQuery

What would be the best way to optimise(shorten) this block of code?. I'm using the Jquery UI plugin 'select menu' to assign to a select number of elements.

$('footer#footer form select').selectmenu({
    style: 'dropdown',
    appendTo: 'footer#footer form span'
});

$('form.filters section.grid .industry select').selectmenu({
    style: 'dropdown',
    appendTo: 'form.filters section.grid .industry'
});

$('form.filters section.grid .subject select').selectmenu({
    style: 'dropdown',
    appendTo: 'form.filters section.grid .subject'
});

$('form.filters section.grid .year select').selectmenu({
    style: 'dropdown',
    appendTo: 'form.filters section.grid .year'
});


$('form.filters section.grid .organiser select').selectmenu({
    style: 'dropdown',
    appendTo: 'form.filters section.grid .organiser'
});

Upvotes: 4

Views: 213

Answers (2)

zzzzBov
zzzzBov

Reputation: 179046

Use classes and [data-*] attributes to pass data to jQuery:

$('select.selectMenu').each(function () {
    $(this).selectmenu({
        style: 'dropdown',
        appendTo: $(this).data('target')
    });
});

This relies on changing the markup so that the select elements have the right class, and have their [data-target] attributes set to the appropriate values.

<select class="selectMenu" data-target="footer#footer form span">
    ...options...
</select>

A couple variations for the each body and HTML:

Using the entire data object:

$(this).selectmenu($(this).data());

<select data-style="dropdown" data-append-to="footer#footer form span">

Using one [data-*] attribute:

$(this).selectmenu($(this).data('selectmenu'));

<select data-selectmenu='{"style":"dropdown","appendTo":"footer#footer form span"}'>

Upvotes: 2

I Hate Lazy
I Hate Lazy

Reputation: 48761

You could a map of "selectors" to the "append" part

var parts = {
    'footer#footer form select'                  : ' span',
    'form.filters section.grid .industry select' : '',
    'form.filters section.grid .subject select'  : '',
    'form.filters section.grid .year select'     : '',
    'form.filters section.grid .organiser select': ''
};

for (var p in parts) {
    $(p).selectmenu({
        style: 'dropdown',
        appendTo: p.replace(" select", parts[p])
    });
}

Or you could do this.

$('footer#footer form select').selectmenu({
    style: 'dropdown',
    appendTo: 'footer#footer form select span'
});

$('form.filters section.grid .row * select').each(function() {
    $(this).selectmenu({
        style: 'dropdown',
        appendTo: $(this).closest('.span3')
    });
});

Upvotes: 1

Related Questions