Get background image information if element has a one in jQuery

Recently I need to loop through elements on a page and, if the element had a background image apply a jQuery plugin. The plugin required the background image path & dimensions to function - however because each image differed in size, it needed to be done programmatically.

There fundamentals of the code are pure JS, so jQuery isn't needed

// Find each object and loop through one by one
$('div').each(function(index, el) {
// Cache the object
var self = $(this);
// Get the background-image
var background = self.css('background-image');
// If the background image is anything other than "none"
if(background != 'none') {
// Find and replace "url()" to get the pure image URL
background = background.replace('url("','').replace('")','');
// Create new Image instance and set path to our background
var bg = new Image;
bg.src = background;
// We now have several vars available to pass through to the plugin
// self = the element
// background = the url
// bg.width = image width
// bg.height = image height
}
});

The code above gets the background image and, if it exists, get the width and height of the image as a variable which can then be passed through to wherever you need!

This website is currently having a full content audit - apologies if some of the code or content looks a bit funky!

View this post on Gitlab

You might also enjoy…

  • Download files via command line

    Posted on 6th March 2016.

    I recently purchased a Western Digital EX2 NAS box for my home storage. This device is a low powered file server which is on all the time - perfect for taking care of those hefty downloads and long running tasks so I don't need to keep my laptop on.

Mike Street

Written by Mike Street

Mike is a front-end developer from Brighton, UK. He spends his time writing, cycling and coding. You can find Mike on Twitter.