Reputation: 14145
inside view page I have several div which id's starts with my-
prefix,
<div id="my-div1"><img src="/img/1.jpg" /></div>
<div id="my-div2"><img src="/img/2.jpg" /></div>
<div id="my-div3"><img src="/img/3.jpg" /></div>
in js code I'm iterating trough each element and I want to apply certain function child img element, in this case backstretch
$(document).ready(function () {
$('div[id^="my-"]').each(function () {
$(this).css("background-size", "100% 100%");
$(this).css("background-repeat", "no-repeat");
// this doesn't work
$(this).children("img").backstretch($(this).attr('src'));
})
});
when I test $(this).children("img").length
returns actual number of img under each div but I dont know how to pass it's src attribute value to backstretch function?
Upvotes: 0
Views: 90
Reputation: 1074028
Based on the documentation, it doesn't look like backstretch
supports passing in a function (the way may jQuery setter functions do), so you're stuck with each
:
$(this).children("img").each(function() {
$(this).backstretch(this.src);
});
Note that I'm not bothering to use jQuery for accessing the src
, there's already a DOM property there ready and waiting. :-)
Or if you want to apply backstretch
to the div, since each div only has one image, you can do this:
$(this).backstretch($(this).find("img").attr("src"));
attr
will return the src
of the first image in the div.
And finally, since backstretch
supports multiple images as a slideshow, if your divs were going to have more than one image, you could use children("img").map(...).get()
to get an array of their src
attributes:
$(this).backstretch($(this).children("img").map(function() {
return this.src;
}).get());
Upvotes: 3
Reputation: 3104
Try this:
$(document).ready(function () {
$('div[id^="my-"]').each(function () {
$(this).children("img").each(function() {
$(this).backstretch($(this).attr("src"));
});
})
});
Upvotes: 0