Sam Provides
Sam Provides

Reputation: 259

Add background image to a div via javascript

<div class="splash-image-wrap splash-image">
<img class="splash-image-bg" src="http://mysite-com/image.jpg" alt="image-bg">
</div>

Can you help me with a script that adds the img src url as image background for the wrap div?

I'm trying this but does not work

$(function () {

function updatePageForTopImg(){
    // background image using size cover
    // top background image
    $('.splash-image-wrap').css('background-image', 'url('+$(".splash-image-bg").attr("src")+')').css('background-size' , 'cover').css('background-position' , 'top center');
}
$(window).on('load', function(){
updatePageForTopImg();
});
});

Upvotes: 1

Views: 1685

Answers (3)

David Li
David Li

Reputation: 1290

You want to keep things that are static in your css file, such as background-size and background-position.

JS:

$('.splash-image-wrap').css({
    background-image: 'url(" + $('.splash-image-bg').attr('src') + ")'
});

CSS:

.splash-image-bg {
    background-size: cover;
    background-position: center top;
}

Also as a sidenote, you do not need window.load or document.ready in your code after you have wrapped it like $(function(){}).

window.load is used for waiting for inner frames and images to load. Since you haven't injected your background image yet, you do not need to wait for this to run your code.

Also, document.ready is equivalent to wrapping your function like $(function() {, which you are already doing. You can completely scrap these and have it still work.

Upvotes: 2

Canvas
Canvas

Reputation: 5897

You have the correct code, however not sure why you have a $(window).load. Here is a working version

jsFiddle : https://jsfiddle.net/CanvasCode/rn7ejrke/1/

jQuery

function updatePageForTopImg() {
        // background image using size cover
        // top background image
        $('.splash-image-wrap')
            .css('background-image', 'url(' + $(".splash-image-bg").attr("src") + ')')
            .css('background-size', 'cover')
            .css('background-position', 'top center');
    }

$(function () {
    updatePageForTopImg();
});

Upvotes: 0

Andrew Slane
Andrew Slane

Reputation: 71

Assuming you're loading the jQuery library, the following should work:

$('.splash-image-wrap').css({
    'background-image': 'url(" + $('.splash-image-bg').attr('src') + ")',
    'background-size': 'cover',
    'background-position': 'top center'
});

If not, you'd need to rewrite your function using vanilla JS.

Upvotes: 0

Related Questions