0

I am trying to create an array images to preload by getting each of the image link in the rel attributes.

I have on a page:

<div id="gallery_thumbs">
  <a><img src="images/image-1-thumb.jpg" rel="images/image-1.jpg" /></a>
  <a><img src="images/image-2-thumb.jpg" rel="images/image-2.jpg" /></a>
  <a><img src="images/image-3-thumb.jpg" rel="images/image-3.jpg" /></a>
  <a><img src="images/image-4-thumb.jpg" rel="images/image-4.jpg" /></a>
</div>

When the page loads I need to get all the rel attributes in the #gallery_thumbs a img and append these to an array like so:

preload([ 'images/image-1.jpg', 'images/image-2.jpg', 'images/image-3.jpg', 'images/image-4.jpg']);

Can anyone help?

1
  • for formatting, just highlight the section of code and click the 101010 button up top, it'll space it over 4 spaces...and markdown will format it nicely for you. Click edit above to see how the formatting looks after I tweaked it :) Commented Nov 30, 2010 at 14:40

2 Answers 2

3

You can use .map() to get an array of the strings you want, like this:

var arr = $("#gallery_thumbs img").map(function() { 
            return $(this).attr("rel"); 
          }).get();
preload(arr);

An <a> without a name or href is invalid though, why not have the href to go the image you want (which would degrade gracefully), and prevent that action in JavaScript? Your markup would look like this:

<div id="gallery_thumbs">
  <a href="images/image-1.jpg"><img src="images/image-1-thumb.jpg" /></a>
  <a href="images/image-2.jpg"><img src="images/image-2-thumb.jpg" /></a>
  <a href="images/image-3.jpg"><img src="images/image-3-thumb.jpg" /></a>
  <a href="images/image-4.jpg"><img src="images/image-4-thumb.jpg" /></a>
</div>

Making the script above simpler too:

var arr = $("#gallery_thumbs a").map(function() { return this.href; }).get();
preload(arr);
Sign up to request clarification or add additional context in comments.

3 Comments

This returns undefined in Firefox??
@Chill - The first? rel is an invalid attribute, so I'd really go with the second if possible.
I still can't seem to get the it to preload from the array,
0

You can use map function:

$("img").map(function(i,e) { return $(e).attr('rel');})

1 Comment

This seems to work but how would you convert the strings into a an array?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.