-1

Hi I need a jQuery function to add a text to src of all images in the page. for example after one minute of load of my page I want to add "mobileserver" to src of all images like this.

<img src="mobileserver/images/sampleimage.jpg" />
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
sun1987
  • 241
  • 1
  • 2
  • 16

2 Answers2

3

You can use setTimeout() to set delay and attr() with callback function for updating the src attribute,

$(document).ready(function () {
   setTimeout(function () {
        $('img').attr('src',function (i,v) {
            return 'mobileserver/' + v;
        });
    }, 60000);
});
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
1

JQUERY ANSWER
As Wolff stated there no point in using setInterval instead of setTimeout

$(document).ready(function () {
    setTimeout(function () {
        $('img').each(function () {
            var nSrc= 'mobileserver/' + $(this).attr('src');
            $(this).attr('src', nSrc);
        });
    }, 60000);
});



EDIT
Since my answer wasn't fully correct, I'm trying to deserve these points, so here it is a pure javascript solution:

(function () {
    setTimeout(function () {
        var imgTag = document.getElementsByTagName("img"),
            count = imgTag.length;
        for (var i = 0; i < count; i++) {
            imgTag[i].setAttribute("src", 'mobileserver/' + imgTag[i].getAttribute('src'));
        }
    }, 60000);
})();

The only problem could be the browser compatibility, check this answer for other method to check if the document is ready:https://stackoverflow.com/a/9899701/1139052

Community
  • 1
  • 1
Razorphyn
  • 1,314
  • 13
  • 37
  • 1
    Why not using a timeout? What is the purpose of `$(this).text(nSrc);`? – A. Wolff May 09 '15 at 16:54
  • Oops sorry, I was trying with `a` tag andI wanted to check the link by printing it – Razorphyn May 09 '15 at 16:58
  • About `setInterval` vs `setTimeout`...if I don't remember wrong with the second one the machine waits untill the function is executed, this doesn't happen with `setInterval` – Razorphyn May 09 '15 at 17:00
  • 2
    No the only difference is that a timeout callback runs only once :) – A. Wolff May 09 '15 at 17:02
  • Well you are right and I was partially right, `setInterval` doesn't care if the previous task has finished or not before run the second one, `setInterval` is less reliable with short intervals – Razorphyn May 09 '15 at 17:14