3

Currently I have a list of elements for an isotope page. The basic markup for an element is:

<div class="element conference-box"> <a href="#"><img src="#" class="conference-image" alt=""></a>
    <div class="caption">
      <div class="confback"></div>
      <h3 class="conference-title"></h3>
      <h4 class="conference-details"></h4>
    </div>
</div>

There around 30 or so elements on the page.

I've been trying to use jQuery to take the image with the class "conference-image" and apply it as a background image to the .confback div, while retaining the original image. I had some success using this code:

$('.element').each(function() {
    var getImageSrc = $('.conference-image').attr('src');
    $('.confback').css('background-image', 'url(' + getImageSrc + ')');
    return true;
});

However, my script takes the image from the very first element and applies that as the background image for every .confback div in every element on my page. Obviously, I would like each individual element to use the image that has been used in that particular element.

2 Answers 2

4

Within the .each callback, the this variable will be the .element that's currently being looped over. You can use that to search within just that element for the img and div you want to work with by re-wrapping it with jQuery and using the find method:

$('.element').each(function() {
    var getImageSrc = $(this).find('.conference-image').attr('src');
    $(this).find('.confback').css('background-image', 'url(' + getImageSrc + ')');
});

Also note, the documentation for .each says:

Use return false to break out of each() loops early.

That doesn't mean you have to use return true to continue the loop, not returning anything is also valid - so I removed it from my example above.

Sign up to request clarification or add additional context in comments.

Comments

0

Inside your .each function $(this) will be the elements with class element. You want to use the attributes and css of it's descendants, found using find:

$('.element').each(function() {
    var getImageSrc = $(this).find('.conference-image').attr('src');
    $(this).find('.confback').css('background-image', 'url(' + getImageSrc + ')');
});

1 Comment

Think you and James wrote the same solution word for word. Thank you both, this worked perfectly!

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.