Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9225537
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T04:36:05+00:00 2026-06-18T04:36:05+00:00

This is the code I have so far, which at the moment loads the

  • 0

This is the code I have so far, which at the moment loads the info from the xml file as desired with javascript. I’ve set it to loop 4 times to select 4 images, but these are obviously just the first 4 from the xml file.

Does anyone know the best way to make it randomly select 4 none repeated images from the xml file.

<script>
if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
    }
else
    {// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.open("GET","include/photoLibrary.xml",false);
    xmlhttp.send();
    xmlDoc=xmlhttp.responseXML;

var x=xmlDoc.getElementsByTagName("photo");
    for (i=0; i<4; i++)
    { 
    document.write('<a href="');
    document.write(x[i].getElementsByTagName('path')[0].childNodes[0].nodeValue);
    document.write('" class="lytebox" data-lyte-options="group:vacation" data-title="');
    document.write(x[i].getElementsByTagName('description')[0].childNodes[0].nodeValue);
    document.write('"><img src="');
    document.write(x[i].getElementsByTagName('thumb')[0].childNodes[0].nodeValue);
    document.write('" alt"');
    document.write(x[i].getElementsByTagName('title')[0].childNodes[0].nodeValue);
    document.write('"/></a>');                      
    }
</script>

If it helps in any way, this is an example of the xml, you’ll see there is an attribute to photo which gives it a unique id.

<gallery>

<photo id="p0001">
<title>Pergola</title>
<path>photos/Pergola.jpg</path>
<thumb>photos/thumbs/Pergola.jpg</thumb>
<description>Please write something here!</description>
<date>
    <day>04</day>
    <month>04</month>
    <year>2006</year>
</date>
</photo>

</gallery>

I’m willing to use php as an alternate to javascript.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T04:36:07+00:00Added an answer on June 18, 2026 at 4:36 am

    First things first. Try not to use document.write as this method acts inconstantly when the DOM is ready vs when it is still initializing. Its considered a bad practice.

    I also recommend using functions to break down the complexity of your code and make it more readable.

    You should be aware that XHR objects are not synchronous. You need to wait for the xml data to be retrieved via the readystatechange event.

    Lastly you don’t have to build strings of html in the browser. The DOM API allows you to create the anchor and image tags as proper nodes which can be attached to the DOM tree.

    Hope that helps.

    (function() {
    
        //fetch the gallery photos
        getXML('include/photoLibrary.xml', function(xml) {
            var photos, pI, photo, anchor, image, anchors = [];
    
            //pick four photos at random
            photos = getRandom(makeArray(xml.getElementsByTagName('photo')), 4);
    
            //build out each photo thumb
            for(pI = 0; pI < photos.length; pI += 1) {
                photo = photos[pI];
    
                //create the anchor
                anchor = document.createElement('a');
                anchor.setAttribute('href', photo.getElementsByTagName('path')[0].childNodes[0].nodeValue);
                anchor.setAttribute('class', 'lytebox');
                anchor.setAttribute('data-lyte-options', 'group:vacation');
                anchor.setAttribute('data-title', photo.getElementsByTagName('description')[0].childNodes[0].nodeValue);
    
                //create the image
                image = document.createElement('img');
                image.setAttribute('src', photo.getElementsByTagName('thumb')[0].childNodes[0].nodeValue);
                image.setAttribute('alt', photo.getElementsByTagName('title')[0].childNodes[0].nodeValue);
    
                //insert the image into the anchor
                anchor.appendChild(image);
    
                //insert the anchor into the body (change this to place the anchors else were)
                anchors.push(anchor);
            }
    
            //when the DOM is loaded insert each photo thumb
            bind(window, 'load', function() {
                var aI;
    
                for(aI = 0; aI < anchors.length; aI += 1) {
                    //replace document.body with whatever container you wish to use
                    document.body.appendChild(anchors[aI]);
                }
            });
        });
    
        /**
         * Fetches an xml document via HTTP method GET. Fires a callback when the xml data
         * Arrives.
         */
        function getXML(url, callback) {
            var xhr;
    
            if(window.XMLHttpRequest) {
                xhr = new XMLHttpRequest();
            } else if(window.ActiveXObject) {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            } else {
                throw new Error('Browser does not support XML HTTP Requests.');
            }
    
            //attach the ready state hander and send the request
            xhr.onreadystatechange = readyStateHandler;
            xhr.open("GET","photos.xml",false);
            xhr.send();
    
            function readyStateHandler() {
    
                //exit on all states except for 4 (complete)
                if(xhr.readyState !== 4) { return; }
    
                //fire the callback passing the response xml data
                callback(xhr.responseXML);
            }
        }
    
        /**
         * Takes array likes (node lists and arguments objects) and converts them
         * into proper arrays.
         */
        function makeArray(arrayLike) {
            return Array.prototype.slice.apply(arrayLike);
        }
    
        /**
         * Extracts a given number of items from an array at random.
         * Does not modify the orignal array.
         */
        function getRandom(array, count) {
            var index, randoms = [];
    
            //clone the original array to prevent side effects
            array = [].concat(array);
    
            //pull random items until the count is satisfied
            while(randoms.length < count) {
                index = Math.round(Math.random() * (array.length - 1));
                randoms.push(array.splice(index, 1)[0]);
            }
    
            return randoms;
        }
    
        function bind(element, eventName, callback) {
            if(typeof element.addEventListener === 'function') {
                return element.addEventListener(eventName, callback, false);
            } else if(typeof element.attachEvent === 'function') {
                return element.attachEvent('on' + eventName, callback);
            }
        }
    })();
    

    Edit: Fixed three errors. The DOM needs to be loaded before inserting the nodes. XML nodes don’t have innerHTML property. Array.concat does not see DOM NodeList objects as Arrays.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have this code so far which perfectly but relies on there being a
This is what I have as far as code, it is in the first
So i have this code which makes a box, but want to make the
I have an XML file which is structured as follows: <row> <store>place1</store> <location>location1</location> </row>
I have the following code which does not seem to be working. As far
I have this array at the moment which contains a lot of data URIs.
this is function.php of a wordpress theme that NOD32 says this code have a
I've used this code to have a like btn on my site: <iframe src=http://www.facebook.com/plugins/like.php?href=URL_OF_YOUR_WEBSITE&amp;send=false&amp;layout=standard&amp;width=450&amp;show_faces=true&amp;action=like&amp;colorscheme=light&amp;font&amp;height=80&amp
Currently I have this code: <?php echo '<meta name=robots content=noindex>'; $arr = json_decode(file_get_contents(http://media1.clubpenguin.com/play/en/web_service/game_configs/ paper_items.json),true);
So I have this code here: <table> <tr> <td width=200px valign=top> <div class=left_menu> <div

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.