Antonin Cezard
Antonin Cezard

Reputation: 2021

Assign an image as a css background image

I'm working on a responsive slider, it's not that easy. Basically it must works from 320px to 1920px, with a fixed height.

So its giving me a headache, I have an easy fix : instead of using the a > image, I will assign the image url as background image for the a, then set the image opacity to 0. So, I will be able to use the cover+center background properties and my slider will be perfect.

But I have problems doing that because I'm unsure how to do it, I spent time yesterday but couldn't assign the image as background.

Here is what the markup looks like (I removed unecessary blocks, just keeping the most importants)

<div class="slide-image"> 
    <a href="xyz.com">
        <img src="image.com/img.jpg">
    </a>
</div>
<div class="slide-image"> 
    <a href="zxy.com">
        <img src="image.com/img2.jpg">
    </a>
</div>

etc ..

I tried that code which doesnt work, the variable gets a value but nothing is assigned :

$(function() {
    if ($('.slider').length) {
        $('.slider').slick({});

        $('.slide-image').each(function() {
            var img = $('img', this).attr('src');
            $('a', this).css('background-image', 'url(' + img + ')url');
        };
    }
});

Upvotes: 2

Views: 80

Answers (2)

Keammoort
Keammoort

Reputation: 3075

You're trying to read "src" attribute, but you've set "url" in your HTML. Change your JS:

var img = $('img', this).attr('url');

Also you're assigning wrong style. It should be:

$('a', this).css('background-image', 'url(' + img + ')');

Upvotes: 4

Marcos P&#233;rez Gude
Marcos P&#233;rez Gude

Reputation: 22158

Note you have an error in this line:

 $('a', this).css('background-image', 'url(' + img + ')url'); 
                          ------------------------------^

It must be

 $('a', this).css('background-image', 'url(' + img + ')');

And <img> tag is bad,

 <img url=""> BAD
 <img src=""> GOOD

Upvotes: 2

Related Questions