Reputation: 1304
I'm trying to convert loaded img
tags to background images using jQuery, however, the images are being loaded in a PHP while loop. When I try implementing the jQuery, only the last img
tag is looked at by the jQuery. Here is my code
PHP
$query = mysqli_query($dbleads, "SELECT * FROM plugin_blog WHERE published = 1 ORDER BY date_added DESC LIMIT 0,20");
$i = 0;
$j=-1;
while ($row=mysqli_fetch_array($query)){
preg_match('/(<img[^>]+>)/i', $row['html'], $matches);
$img = $matches[1];
++$i;
if ($i%2 == 0){
++$j;
echo "<div class='masonryImage tweets' style='width:300px; height:175px;'><div class='tweet-content'>" . $tweets[$j] . "</div></div>";
}
else{
echo "<div class='masonryImage blogImage' style='width: 300px; height:200px;'>" . $img . " </div>";
}
}
jQuery
$j('div.blogImage img').each(function() {
var imageSrc = $j(this).attr('src');
$j(this).remove();
$j('.blogImage').html('<div class="backbg"></div>');
$j('.backbg').css('background-image', 'url(' + imageSrc + ')');
$j('.backbg').css('background-repeat','no-repeat');
$j('.backbg').css('background-position','center');
$j('.backbg').css('background-size','cover');
$j('.backbg').css('width','100%');
$j('.backbg').css('height','100%');
});
Any ideas?
Upvotes: 0
Views: 675
Reputation: 64657
You are setting every .backbg's css on the last iteration.
When you run $j('.backbg').css('background-image', 'url(' + imageSrc + ')');
the last time, you are saying "find EVERY .backbg, even the ones I've already done, and set their css".
You need to do something like:
var imageSrc = $j(this).attr('src');
var blogImg = $j(this).parent();
$j(this).remove();
blogImg.html('<div class="backbg"></div>');
blogImg.find('.backbg').css('background-image', 'url(' + imageSrc + ')');
Upvotes: 1