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 becuase each image differed in size, it needed to be done programatically.

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 serveral vars availible 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!

You might also enjoy

  • Useful command line MySQL commands

    Posted on 5th July 2020.

    It seems I have been doing a lot of command line work on Debian with MySQL recently and have been having to search the internet (or my bash history) every time I need to do something. Here is a collection of commands I have been using…

  • The Git Commit Hash

    Posted on 28th May 2020.

    The magic 40 character string that is attached to every commit you do. What is it, where does it come from and will understanding it help you with Git in the future?…

  • Why should you consider Cloudflare for your website?

    Posted on 20th April 2020. Written For Liquid Light

    Cloudflare is a service which, among other things, provides a CDN (Content Delivery Network), firewall, and performance layer for your website. It has plenty of paid upgrades and features and is a developer’s dream, but what advantage does it have for you to put your website “behind” Cloudflare and how…

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.