binaryfunt
binaryfunt

Reputation: 7127

Replace <img> with CSS background image for parent element (using jQuery to separate style from content)

I have a div class, .event, that is supposed to have a background image (different images for each instance of that class). However, I don't want to edit the CSS every time I add a div of this class. I only want to edit the HTML, as is the goal with HTML5, separating the styling from the content.

HTML:

<div class="event" id="meeting1">
  <img src="img/DSC_0001.jpg">
  <span>Mon 19 Oct</span>
</div>
<div class="event" id="bookSale">
  <img src="img/DSC_0004.jpg">
  <span>Wed 21 Oct</span>
</div>
...

Upvotes: 1

Views: 1341

Answers (3)

Chintan Patel
Chintan Patel

Reputation: 79

$(".event img").each(function(index) {
    var src = $(this).attr("src");
    var eventCal = $(this).parent();

    eventCal.css("background", "url(" + src + ") center center/cover no-repeat");
    $(this).hide();
});

I have correct minor mistakes of variable.

Upvotes: 0

Simon E.
Simon E.

Reputation: 58490

Why don't you just inline the styling?

<div class="event" id="meeting1" style="background-image: url(img/DSC_0001.jpg)">
  <span>Mon 19 Oct</span>
</div>
<div class="event" id="bookSale" style="background-image: url(img/DSC_0004.jpg)">
  <span>Wed 21 Oct</span>
</div>

There are some situations where inline styling is frowned upon, but in this case, I would say it is suitable.

Upvotes: 2

binaryfunt
binaryfunt

Reputation: 7127

I have come up with a sort of polyfill using jQuery. It uses .each() to find each <img> element within an .event div and hide it, and adds a background image to the CSS.

JavaScript:

$(document).ready(function() {

    $(".event img:first").each(function(index) {

        var src = $(this).attr("src");
        var eventCal = $(this).parent();

        event.css("background", "url(" + src + ") center center/cover no-repeat");
        $(this).hide();
    });
});

This has the bonus of not downloading the images twice (in theory), as they should already be cached.

Upvotes: 1

Related Questions