0

I have slightly refined my question from the generic "detect image" question I posted earlier.

I want to detect the background image and once that has been done, remove a class from a totally different element within the DOM.

HTML:

<div class="rh-big-hero-wrapper" style="background-image:url('bg-sample-10.jpg');">

JS:

$(function() {
'use strict';

    var heroElem = $('.rh-big-hero-wrapper');
    var imgElem = ('bg-sample-10.jpg');
    var visClass = $('rh-notvisible');

           // hides article product relation in hero.  
    $('.rh-big-hero-heading-product-item-inner').addClass('rh-notvisible'); {
        //console.log('class has been added...just checking, cause Im loosing my mind');
    };


    heroElem.css('background-image');
        // console.log(heroElem);
    heroElem.find(imgElem); {
        // console.log('displaying', imgElem);
    if($(this).is(':visible')) {
        console.log(imgElem, 'is visible');
        $('.rh-big-hero-heading-product-item-inner').removeClass(visClass);
        };
    } });

Thank you for your advice, solutions and guidance in advanced.

ambtlv
  • 45
  • 1
  • 5
  • Possible duplicate of [Detect specific image is loaded then do something...](https://stackoverflow.com/questions/44197140/detect-specific-image-is-loaded-then-do-something) – Alive to die - Anant May 26 '17 at 12:25
  • Do you need to check if certain element has an specific background-image, or, if the image is applied as background-image to any element (so check if it is present)? – Alvaro May 26 '17 at 12:29
  • @Alvaro - it could be both, but for now I will go with a specific image being present and applied to the div element. Hope that makes sense? – ambtlv May 26 '17 at 12:32
  • I am not sure if I understood correctly now that I read the first comment. You need to check if an image is assigned or if it already loaded? (my confusion comes from "being present") – Alvaro May 26 '17 at 12:49
  • @Alvaro ...sorry, already loaded. – ambtlv May 26 '17 at 12:51
  • @ambtlv I see. I edited the answer, hope it is what you were looking for. – Alvaro May 26 '17 at 13:07

1 Answers1

0

You could create a virtual image and assign it as src the path of the image you are looking for (background-image in this case). Then assign it a load event and listen to it:

var element_backgroundimage = $('#element').css('background-image'),// url("image.jpg")
    image_value = element_backgroundimage.replace('url(', '').replace(')', '').replace(/\"/gi, ''),
    $img = $('<img src="' + image_value + '" />');

$img
    .one('load', function() {

        console.log("loaded");// Do something here

    })
    .filter(function() { // If the image is already loaded, trigger the above load function

        if (this.complete) {
            $img.load();
        }

    });

JSFiddle demo


(Get the image path from the background-image url property credits.)

Alvaro
  • 9,247
  • 8
  • 49
  • 76