Rebecca Cook
Rebecca Cook

Reputation: 111

Changing img src using jQuery

**Disclaimer: I'm writing a theme file for a web app that doesn't allow me to manipulate the core files of the app, so I cannot change the order in which files load in the DOM.

I have a JS file that allows me to add custom scripts to the page. I am coding in jQuery.

I want to change the image source of one of the elements on the page. The image's source is loaded to the page dynamically by a core JS file that I cannot touch, that is loaded after my file...

Let's say the HTML is:

<div class ="parent">
    <img src="http://example.com/image.jpg">
</div>

When I add something like the following to my jQuery doc:

$(document).ready(function(){
    function fixImgSrc(){
        var newSrc = 'http://example.com/new-image.jpg';
        var image = $('.parent').find('img');
        if (image.attr('src') !== newSrc){
            image.attr('src', newSrc);
        }
    };
    fixImgSrc;
});

When I run this function, it returns undefined since images are loaded after the jQuery. I need to do this multiple times throughout the code to correct images. Sometimes I can get around this by running the function as:

 setTimeout(fixImgSrc(), 500);

which runs the function after everything else has loaded. Other times the only way I can get this to work throughout the site is by doing the miserable:

 setInterval(fixImgSrc(), 500);

to keep checking if the new source has been taken.

Is there a better less tacky way to do this? This seems like it's a hack and not the "right" way to do it. Plus the load on the browser is intense running the same command over and over again.

Upvotes: 0

Views: 56

Answers (2)

Osama
Osama

Reputation: 3040

$(document).ready(function(){
FixImgSrc();
}

Here it will let the function work after the ready state of the document

Try this

    var image = $('.parent').find('img');
image.on("load",function(){
    if (image.attr('src') !== newSrc){
        image.attr('src', newSrc);
}

Upvotes: 1

waleed bin khalid
waleed bin khalid

Reputation: 112

  $(document).ready(function(){
   alert("ready ");
   FixImgSrc();
  }

I think first you need to check is your jquery is working or not.

Upvotes: 1

Related Questions