views:

132

answers:

4

I have the following jquery which I want to simplify.

I am just repeating the same things.

Could anyone give me suggestions please.

Thanks in advance.

$("a[rel='imagebox-all']").colorbox({slideshow:true});
$("a[rel='imagebox-new']").colorbox({slideshow:true});
$("a[rel='imagebox-even']").colorbox({slideshow:true});
$("a[rel='imagebox-amina']").colorbox({slideshow:true});
$("a[rel='imagebox-cumulus']").colorbox({slideshow:true});
$("a[rel='imagebox-wee']").colorbox({slideshow:true});
$("a[rel='imagebox-four']").colorbox({slideshow:true});
$("a[rel='imagebox-teen']").colorbox({slideshow:true});
+12  A: 

Assuming there are no other values of imagebox-* you want to exclude:

$("a[rel^='imagebox-']").colorbox({slideshow:true});

That being said, attribute selectors are usually best avoided and you're typically better off restructuring your problem to allow a better solution. Like you could use classes:

<a href="..." class="imagebox teen"> ...

Note the space: that's two classes assigned. So you can do:

$("a.imagebox")...

for all of them. Or:

$("a.imagebox.teen")...

for just one of them.

Remember as well you can add multiple selectors with a comma:

$("a.class1, a.class2")...

will apply what you're doing to anchors with class1 OR class2 versus:

$("a.class1.class2")...

which applies whatever you're doing to anchors that have class1 AND class2.

cletus
+3  A: 

You can user the attributeStartsWith selector which matches elements that have the specified attribute and it starts with a certain value.

$("a[rel^='imagebox-']").colorbox({slideshow:true});
rahul
A: 

Try this:

var selectors = [
    "a[rel='imagebox-all']",
    "a[rel='imagebox-new']",
    "a[rel='imagebox-even']",
    // ...
];

$.each(selectors, function(){
    $(this).colorbox({slideshow:true});
});

Then, whenever you need to add a new selector, just add it to the selectors array.

jboxer
+1  A: 

Could you use

$("a[rel^='imagebox']").colorbox({slideshow:true});

which applies to any a tag with a rel attribute that starts with imagebox?

Jason Aller