SDD
SDD

Reputation: 23

Get Image Source URLs from a Different Page Using JS

Everyone:

I'm trying to grab the source URLs of images from one page and use them in some JavaScript in another page. I know how to pull in images using JQuery .load(). However, rather than load all the images and display them on the page, I want to just grab the source URLs so I can use them in a JS array.

Page 1 is just a page with images:

<html>
  <head>
  </head>
  <body>
    <img id="image0" src="image0.jpg" />
    <img id="image1" src="image1.jpg" />
    <img id="image2" src="image2.jpg" />
    <img id="image3" src="image3.jpg" />
  </body>
</html>

Page 2 contains my JS. (Please note that the end goal is to load images into an array, randomize them, and using cookies, show a new image on page load every 10 seconds. All this is working. However, rather than hard code the image paths into my javascript as shown below, I'd prefer to take the paths from Page 1 based on their IDs. This way, the images won't always need to be titled "image1.jpg," etc.)

<script type = "text/javascript">
        var days = 730;
        var rotator = new Object();
        var currentTime = new Date();
        var currentMilli = currentTime.getTime();
        var images = [], index = 0;
        images[0] = "image0.jpg";
        images[1] = "image1.jpg";
        images[2] = "image2.jpg";
        images[3] = "image3.jpg";
        rotator.getCookie = function(Name) { 
            var re = new RegExp(Name+"=[^;]+", "i"); 
            if (document.cookie.match(re)) 
                return document.cookie.match(re)[0].split("=")[1];
                return''; 
        }
        rotator.setCookie = function(name, value, days) { 
            var expireDate = new Date();
            var expstring = expireDate.setDate(expireDate.getDate()+parseInt(days));
            document.cookie = name+"="+value+"; expires="+expireDate.toGMTString()+"; path=/";
        }
        rotator.randomize = function() {
            index = Math.floor(Math.random() * images.length);
            randomImageSrc = images[index];
        }
        rotator.check = function() {
            if (rotator.getCookie("randomImage") == "") {
                rotator.randomize();
                document.write("<img src=" + randomImageSrc + ">");
                rotator.setCookie("randomImage", randomImageSrc, days);
                rotator.setCookie("timeClock", currentMilli, days);
            }
            else {
                var writtenTime = parseInt(rotator.getCookie("timeClock"),10);
                if ( currentMilli > writtenTime + 10000 ) {
                    rotator.randomize();
                    var writtenImage = rotator.getCookie("randomImage")
                    while ( randomImageSrc == writtenImage ) {
                        rotator.randomize();
                    }
                    document.write("<img src=" + randomImageSrc + ">");
                    rotator.setCookie("randomImage", randomImageSrc, days);
                    rotator.setCookie("timeClock", currentMilli, days);
                }
                else {
                    var writtenImage = rotator.getCookie("randomImage") 
                    document.write("<img src=" + writtenImage + ">");
                }
            }
        }
        rotator.check()
    </script>

Can anyone point me in the right direction? My hunch is to use JQuery .get(), but I've been unsuccessful so far.

Please let me know if I can clarify!

Upvotes: 2

Views: 7373

Answers (3)

Mike H.
Mike H.

Reputation: 1751

why not use ajax? you could .load() the section of your external page that contains all of the images into a hidden container and then extrapolate the information you need through a callback.

external.html

<html>
....
    <div id="imgContainer">
         <img id="image0" src="image0.jpg" />
         <img id="image1" src="image1.jpg" />
         <img id="image2" src="image2.jpg" />
         <img id="image3" src="image3.jpg" />
    </div>
</html>

ajax.js

function ajaxContent(reg, extReg) {

var toLoad = 'external.html' + extReg;

function loadContent() {
    $(reg).load(toLoad,'',getSrcPaths())
}

function getSrcPaths() {
    $(reg + ' #image0').delay(200).fadeIn('slow');
    $(reg + ' #image1').delay(200).fadeIn('slow');
    // or however you want to store/display the images
}
}

Then onload just make a call to ajaxContent something like

<body onload="ajaxContent('#hiddenContainer','#imgContainer')">
     ....
</body>

This of course is not really relevant if your images are large or if page load is negatively affected. Although since you actually have the images now, you might even just display them rather than hide them. Depends on exactly how much you need to manipulate the originals I suppose.

Upvotes: 0

mukama
mukama

Reputation: 979

Try this.

<script>
$.get('http://path/to/page/1', function(data) {
    var imgs = $('<div/>').html(data).find('img');
    imgs.each(function(i, img) {
        alert(img.src); // show a dialog containing the url of image
    });
});
</script>

Upvotes: 2

saml
saml

Reputation: 6802

I don't understand why you want to use cookies for this. You should get page1, find the images, and then use setInterval to update the src.

$.get('page1.html', function(data, status) { // get the page with the images
    var parser = new DOMParser();
    var xmldoc = parser.parseFromString(data, "text/html");  //turn it into a dom

    var imgs = xmldoc.getElementsByTagName('img'); //get the img tags
    var imageSrcs = Array.prototype.slice.call(imgs).map(function(img) {
       return img.src; //convert them to an array of sources
    });

    setInterval(function() { // run this every 10 seconds
        var imags = document.getElementsByTagName('img'); // find the images on this page
        Array.prototype.slice.call(imgs).forEach(function(img) {
             var imgSrc = Math.floor(Math.random()*imageSrcs.length);  //get a random image source
             img.src = imageSrcs[imgSrc];  //set this image to the src we just picked at random
        });
    }, 10000);

}, 'html');

Upvotes: 1

Related Questions