Bijan
Bijan

Reputation: 8586

jQuery dynamically create elements

I have a javascript function that uses ColorBox. The <a rel link points to a folder that is automatically assigned to the date (i.e. 20140806). How would I make this more efficiently so I do not have to do it for every single date like the example below

<script type="text/javascript">
$(document).ready(function(){
    $("a[rel='20140804']").colorbox();
    $("a[rel='20140805']").colorbox();
    $("a[rel='20140806']").colorbox();
});
</script>

Upvotes: 0

Views: 62

Answers (3)

Клаус Шварц
Клаус Шварц

Reputation: 3268

As Rocket Hazmat said, you can add a CSS class to the links you want to apply colorbox to. At the same place, where you form your HTML links and rel attributes, you will have to add a CSS class, so your HTML will be like that:

<a href="/link/to/the/folder_1" class="colorbox-me">Folder 1</a>
[...]
<a href="/link/to/the/folder_N" class="colorbox-me">Folder N</a>

<script type="text/javascript">
$(document).ready(function(){
    $("a.colorbox-me").colorbox();
});
</script>

It is also discouraged to use rel attribute for any purpose except describing relations of current document with the linked document. rel attribute is usually used by search engines. Possible values of rel attribute may be found here.

Upvotes: 0

user2274060
user2274060

Reputation: 904

You can do also :

$("a").each( function(){

   if ( $(this).attr(rel) == 'myValue' ){
       $(this).colorbox();
   }
});

For every hypertext in your document, you check whether if the 'rel' attribute matches with what you want

Upvotes: 0

Paul Roub
Paul Roub

Reputation: 36438

You can use prefix matching to catch any rel attribute starting with 201 (or 20, to work for the rest of the century):

$(document).ready(function(){
  $("a[rel^='201']").colorbox();
});

See Attribute Starts With Selector

Upvotes: 1

Related Questions