Jon Catmull
Jon Catmull

Reputation: 12752

How do I get multiple image URLs from background CSS attribute?

I have made a small plugin which checks to see if a element(s) background image has loaded.

In doing this I needed to extract the URL of the background image, I have managed to do it when there is just one background image:

var bgURL = $('#myelement').css('background-image').replace(/^url\(["']?/, '').replace(/["']?\)$/, '');

However I want to make my plugin support elements with multiple background images

Here is a code pen example of the code in action if it helps.

It would be good if it worked for any css format e.g. both:

background-image: url(sheep.png), url(betweengrassandsky.png);
background-position: center bottom, left top;
background-repeat: no-repeat;

and

background: url(sheep.png) center bottom no-repeat, url(betweengrassandsky.png) left top no-repeat;

Ideally the result would be an array of the urls (e.g. 0 => ['sheep.png'], 1 =>['betweengrassandsky.png'])

Thanks in advance guys.

Upvotes: 1

Views: 1157

Answers (2)

Hristo
Hristo

Reputation: 117

Obviously you came to the same idea before I can submit, but anyway, I have already written the code... :) Actually, if you use "url" for your split function, you don't have to check if the background has one url or many - idx will be always at least 0 and 1, and you will need to catch always the entries >0.

// Loop through elements
    this.each(function(){
        var Obj = $(this);
        $.each( Obj.css('background-image').split("url"), function(idx, value){
            if (idx>0){
                 //The stuff you're doing with the img tag
                 $('<img/>').attr('src', value.replace( /\(["']?/,'' ).replace( /["']?\),?/,'' )).load(function(){
                     $(this).remove(); // prevent memory leaks
                     settings.afterLoaded.call(Obj);
                 });                }
        });
    });

Upvotes: 1

Jon Catmull
Jon Catmull

Reputation: 12752

Thanks to artm for his idea.

I split the background image by ", " and then run a foreach loop over the array running my existing replace methods.

This is essentially what I did:

var array = [];
$.each($('#myElement').css('background-image').split(', '), function(key, value){
    array.push(value.replace(/^url\(["']?/, '').replace(/["']?\)$/, ''));
});

Here is a working code pen:

http://codepen.io/catmull/pen/Hhufw

You can download the plugin that detects page load from here as well

http://catmull.uk/code-lab/background-image-loaded/

Upvotes: 2

Related Questions