Jump to content

JavaScript Commenting


rbrennan

Recommended Posts

Would someone be able to comment this JavaScript for me to help give me a better understand of what the actual code is doing (I am still a learner) Thanks

<script type="text/javascript"><!--function rotator(options) {var a = options.delay;var b = options.media;var mediaArr = []; for(var i = 0, j = b.length; i < j; i++) { mediaArr.push(b[i].img);} document.write('<div id="rotatorContainer"></div>');var container = document.getElementById('rotatorContainer');var Start = 0; rotatorCore(); function rotatorCore() {Start = Start + 1; if(Start >= mediaArr.length)Start = 0;container.innerHTML = mediaArr[Start];//console.log(Start);setTimeout(rotatorCore, a); } } rotator({delay : 2500, media : [{img : '<img src="Example.jpg" width="212" height="300" border="0" />'}]});// --></script>

Link to comment
Share on other sites

Can I just say that I really hate this code?

function rotator(options) {    // extract the number of milliseconds each image will be displayed    var a = options.delay;        // extract the array of image objects    var b = options.media;        // create an empty array    var mediaArr = [];    // loop through the array of image objects    for(var i = 0, j = b.length; i < j; i++) {            // extract the HTML for each image and push it into the mediaArr array        mediaArr.push(b[i].img);    }    // create an empty div element    document.write('<div id="rotatorContainer"></div>');        // get a reference to that div    var container = document.getElementById('rotatorContainer');        // create a counting variable initialized to 0    var Start = 0;    // call the rotatorCore function defined below    rotatorCore();    // define the rotatorCore function    function rotatorCore() {            // increase the value of the counter by 1        // this counter will be used to "walk through" the array of images        // note that start retains its value whenever the function is called because        // it "exists" in the parent scope of this function.        Start = Start + 1;        // if the value of the counter exceeds the number of images in mediaArr ...        if(Start >= mediaArr.length)                    // reset the counter to 0; this lets the images rotate forever            Start = 0;                // set the inner HTML of the container div to the text of the next element in        // the mediaArr array        container.innerHTML = mediaArr[Start];                // call this function again after a number of milliseconds        setTimeout(rotatorCore, a);    }}// call the rotator function defined above// pass it an object containing two pieces of informationrotator(    // create an object    {        // the first property of the object is the time each image will be displayed        delay : 2500,                // the second property of the object is an array of objects        media : [                    // create an object            {                // the first property of the object is a string                // the string is HTML that can be used to create an image element                img : '<img src="satan.jpg" width="128" height="128" border="0" />'            }            // if desired, add as many image objects as you want to rotate            // be sure to separate them with commas                // close the media array        ]    // close the object that gets passed to rotator    });

  • Like 1
Link to comment
Share on other sites

1. It's wasteful to store so much data as strings of HTML. All you really need to store is an array of URLs. Or, if you want to preload the images, an array of image objects. 2. It's wasteful to replace an entire HTML element just to change an image. Normally, you'd have one permanent image element, and to change the image, you'd update the src attribute. Don't even set the width and height properties; they will take care of themselves. 3. The media array passed to rotator() is weird. It doesn't need to be an array of objects. It can just be an array of strings. 4. I always cringe when I see document.write(). Tutorial writers use it to simplify things, but it encourages bad habits.

Link to comment
Share on other sites

I did make this one that was less wasteful but I just could not get it to work for the life of me, it preloaded the images and change the scr attribute. The document.write is what I have been taught and I am still learning, what is a good alternative to use instead of that? Once again, thanks for the help This is the one that I could not get to work

<script type="textjavascript"><!---//store an interval in a variablevar pause = 1500;//create and intialize a countervar n = 0;//create an array of image file namesvar imgs = new Array("Img1.jpg","Img2.jpg","Img3.jpg");//preload all the imagesvar preload = new Array();for( var i = 1; i<imgs.length;i++){peeload[i] = new Image();preload[i].src = imgs[i];}//a function to display each image for the set intervalfunction rotate(){document.images.pic.src = imgs[n];(n == (imgs.length - 1)) ? n = 0 : n++;setTimeout("rotate()", pause);}//specify the onload event-handlerwindow.onload=rotate;--></script>

Edited by rbrennan
Link to comment
Share on other sites

As to document.write, you have options. If you want to report values in response to a click or something, you can have a textarea and just update it's value.

document.getElementById("ta").value += newValue + "\n"; // the newline lets you keep a running record

or you could change the innerHTML of a div or <p> or something:

document.getElementById("myDiv").innerHTML = newValue;

If you want to create an element dynamically, look into document.createElement(). The big problem with document.write is that if you use it after the document loads, you will delete the entire document and start fresh. Usually that's not what people want.

Edited by Deirdre's Dad
Link to comment
Share on other sites

even better than writing to the page merely for debugging (IMO), is to leverage the browsers console, and write debugging statements right to it. The benefit is it keeps you page clean, and for arrays and objects, a good console like in Chrome will allow you expand through and allow for a detailed inspection of every index/property. not only that, anytime you are writing javascript, you should probably have the console open anyway to check for errors and the like.https://developer.mo...ocs/DOM/console

Edited by thescientist
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...