Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 15 of 15
  1. #1
    New Coder
    Join Date
    Nov 2006
    Location
    Washington, DC
    Posts
    30
    Thanks
    3
    Thanked 0 Times in 0 Posts

    problem with auto-reloading random img

    hi, everyone, I'm struggling to figure out how to make my image automatically reload. particularly when the image is randomly selected from a folder.

    The timing seem to work as the first image disappear after 5 seconds as dictated in the first JavaScript but it simply stays black. Why is the next images not being loaded?

    http://www.lost-ear-studio.com
    I'm new with JavaScript big time and tonight is the first time I've really dived into it.

    Thank you for any advice.

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Lost Ear Studio</title><link rel="stylesheet" href="style.css" type="text/css" />
    
      <script type="text/javascript">
        window.onload = startInterval;	
        function startInterval()
        {
            setInterval("startTime();",5000);
        }
    
        function startTime()
        {
            document.getElementById('time').innerHTML = Date();
        }
    </script>
    
    <script type="text/javascript">
    	function resizeToMax(id){
        myImage = new Image() 
        var img = document.getElementById(id);
        myImage.src = img.src; 
        if(myImage.width > myImage.height){
            img.style.width = "100%";
        } else {
            img.style.height = "100%";
        }
    }
    </script>
    
    </head>
    
    <body>
    
    <div id="time">
    
    <script type="text/javascript" language="JavaScript">
    NumberOfImagesToRotate = 107;
    FirstPart = '<img id="bg" src="images/bg/bg_';
    LastPart = '.jpg" onload="resizeToMax(this.id)">';
    function printImage() {
    var r = Math.ceil(Math.random() * NumberOfImagesToRotate);
    document.write(FirstPart + r + LastPart);
    }
    </script>
    
    <script type="text/javascript" language="JavaScript">
    printImage();
    </script>
    
    </div>

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,103
    Thanks
    80
    Thanked 4,554 Times in 4,518 Posts
    Ummm...your code doesn't even come close to making sense.

    You do this:
    Code:
         document.getElementById('time').innerHTML = Date()
    Do you understand at all what that is doing?

    It is getting the current time and date and replacing the contents of your <div id="time"> with it. And guess where your image *was*? Yep, in that div. So bye bye image.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #3
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,103
    Thanks
    80
    Thanked 4,554 Times in 4,518 Posts
    You need to solve several problems at once, here.

    First of all, because you are loading such large images, it takes a couple of seconds over even a DSL line for each new image to appear. And that means that it will look pig snot ugly.

    So what you need to do is *PRELOAD* the next image while each "current image" is showing. That way the loading time is hidden from view.

    Also, you really should *never* use document.write. It's really bad practice and should be considered obsolete.

    Let me make a stab at rewriting this for you.

    Back later....
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #4
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,103
    Thanks
    80
    Thanked 4,554 Times in 4,518 Posts
    (Even your random number picker is wrong, by the by. It would sometimes pick image number 108. KABLOOEY!)
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #5
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,103
    Thanks
    80
    Thanked 4,554 Times in 4,518 Posts
    You also have a bunch of illegal HTML in there. You can only use an ID *ONCE* per page. If you want to use something for the purpose of applying a style sheet, use a class instead.

    So in your CSS file, instead of #body1 to specify a style, you would then use .body1

    And change <div id="body1"> to <div class="body1">
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #6
    Banned
    Join Date
    Apr 2011
    Posts
    656
    Thanks
    14
    Thanked 69 Times in 69 Posts
    Parts of your code doesn't make sense to me either.

    I assume you want a simple random image rotator. Below is a basic example. It rotates random images and after each image is displayed, it preloads the next random image so you can get a smooth image swap over.

    Code:
     
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
        <head>
            <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
            <title></title>
            <style type="text/css">
                #rndImg {
                    display: none;
                }
            </style>
            <script type="text/javascript">
                var picPaths = ['num1.jpg','num2.jpg','num3.jpg','num4.jpg','num5.jpg','num6.jpg'];
                var curPic = -1;
                function getRandPicNum(){
                    return Math.floor(Math.random()*picPaths.length);
                }
                function swapPicNum(){
                    var newPic = getRandPicNum();
                    while(newPic == curPic){ //ensure next image is not the same as the current image
                        newPic = getRandPicNum();
                    }
                    curPic = newPic;
                }
                function changeImage(){
                    rndImgO.src = nextImage.src;
                    preloadNextImage();
                }
                function preloadNextImage(){
                    swapPicNum();
                    nextImage = new Image();
                    nextImage.src = picPaths[curPic];
                }
            </script>
        </head>
        <body>
            <div id="rndImgCont">
                <img id="rndImg" src="" alt="" />
            </div>
            <script type="text/javascript">
                var  rndImgO = document.getElementById('rndImg');
                preloadNextImage();
                changeImage();
                rndImgO.style.display='inline';
                setInterval(changeImage,5000);     
            </script>
        </body>
    </html>

  • Users who have thanked webdev1958 for this post:

    Radscientist (03-03-2012)

  • #7
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,103
    Thanks
    80
    Thanked 4,554 Times in 4,518 Posts
    Okay...here you go. See next message for some really needed improvements.

    NOTE: I chopped off everything below the <div id="contents"> just for brevity's sake. You can put that all back in.

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Lost Ear Studio</title>
    <link rel="stylesheet" href="http://www.lost-ear-studio.com/style.css" type="text/css" />
    <script type="text/javascript">
    var NumberOfImagesToRotate = 107; // 1 to 107
    
    var imageBase = "http://www.lost-ear-studio.com/images/bg/bg_$$.jpg";
    
    var nextReady = false;
    var nextImageNum = 0;
    
    
    function startUp( )
    {
        // pick first image at random:
        nextImageNum = 1 + Math.floor( NumberOfImagesToRotate * Math.random() );
        // and pretend it is ready:
        nextReady = true;
        // and so get started:
        showNextImage();
    }
    
    function showNextImage()
    {
        if ( ! nextReady )
        {
            // still waiting for next image to finish loading
            setTimeout( showNextImage, 250 ); // try again in a quarter second
            return; // and do nothing more
        }
        // okay...put next image in place in visible image:
        document.getElementById("bg").src = imageBase.replace("$$",nextImageNum);
    
        // then pick the next image:
        var priornum = nextImageNum;
        while ( priornum == nextImageNum ) /* so we don't pick same twice in a row */
        {
            nextImageNum = 1 + Math.floor( NumberOfImagesToRotate * Math.random() );
        }
        nextReady = false;
        // load that next image into the hidden image:
        document.getElementById("nextImage").src = imageBase.replace("$$",nextImageNum);
        // and then wait a minimum of 5 seconds before displaying next one
        // (it will be longer if the next image hasn't finished loading into hidden image)
        setTimeout( showNextImage, 5000 );
    }
    
    window.onload = startUp;
    </script>
    </head>
    
    <body>
    <div style="position: absolute; visibility: hidden; z-index: 100;">
        <img id="nextImage" alt="next image" style="width: 50%; height: 50%;" onload="nextReady=true;" />
    </div>
    <div id="time">
        <img id="bg"style="width: 100%; height: 100%;" alt="main image" />
    </div>
    <div id="contact">
        <div class="testimonial" style="position: relative;">
            <div id="right"><!-- should be class= -->
                <img src="http://www.lost-ear-studio.com/images/head.jpg" width="115" height="116" />  
            </div>
            <p><strong>Contact:</strong></p>
            <p>Jeffery Stroud</p>
            <p>800 Florida Ave NE</p>
            <p>Washington, DC 20002</p>
            <p>(443)312-9005</p>
            <p><a href="mailto:will@lost-ear-studio.com">will@lost-ear-studio.com</a></p>
            <p></p>
            <p>&nbsp;</p>
            <p>Please be aware that I am deaf. So my phone number is from Google Voice, 
               allowing me to get a rough transcription of any voicemails you may leave. 
               Text messages are welcome.</p>
            <div align="middle">
                <a href="aim:goim?screenname=nerddragon"><img src="images/aim.png"/></a>
                <a href="https://www.facebook.com/lostearstudio"><img src="images/facebook.png"/></a>
                <a href="http://www.linkedin.com/pub/jeffery-stroud/29/99/39a"><img src="images/linkedin.png"/></a>
                <a href="https://twitter.com/#!/lostearstudio"><img src="images/twitter.png"/></a>
                <a href="https://plus.google.com/u/0/109327038370401662804/posts"><img src="images/google.png"></a>
            </div>
            <div id="right"><!-- should be class= -->
                <a href="#" onclick="document.getElementById('contact').style.display='none';return false;">Close this</a>
            </div>
        </div>
    </div>
    </body>
    </html>
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    Radscientist (03-03-2012)

  • #8
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,103
    Thanks
    80
    Thanked 4,554 Times in 4,518 Posts
    webdev's answer is great, but it misses one of the problems with your site: Your images are so large that many of them take longer than 5 seconds to load (at least on my DSL connection).

    In my code, I solved that by having the next image load into a hidden image and only setting a "ready" flag when it is loaded. I use the onload of that hidden image to then change the state of my "ready" flag and only load the main image when the flag says the next image is indeed ready. Without this, you would flip to the next image but it would still be only half loaded and the result looks ugly.

    You *REALLY* need to go through *ALL* your pictures and resize them and/or set them to a lower JPEG quality so that they will load faster.

    Another thing that would improve the page would be to find a very simple image that you could encode with a lower JPEG quality and keep its size down nice and small and have that come up *ALWAYS* as your first image. That way, the first image would appear right away. As it is, if the random number generator happens to pick one of your larger images it can take 10 seconds (or more) before the first image is fully loaded.

    By the by, note my simple trick to use your image numbers from 1 to 107: Just add 1 to the random number generator's choice (which will be 0 to 106).

    If you do decide on a "standard" first image, I will show you how to make a minor tweak in my code to use it. (I might suggest that you create a custom image which has just text on it...perhaps your name...in only a few colors. That will compress nicely to almost nothing in JPEG and will load nice and fast.)

    Oh...and I got annoyed at your face staring at me all the time, so I added a "close" button to turn you off. <grin/>
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #9
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,103
    Thanks
    80
    Thanked 4,554 Times in 4,518 Posts
    Actually, that "Rose Eyed" image would compress down nicely. Maybe use that for your initial startup image, always?
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #10
    Banned
    Join Date
    Apr 2011
    Posts
    656
    Thanks
    14
    Thanked 69 Times in 69 Posts
    I can't think of any situation at all where anyone could rightly justify having images that take 5 seconds to download on any type of connection.

    With the image optimisation tools in Photoshop and similar applications, you'll be hard pressed to give me an image that cannot be optimised to download within a couple of seconds - absolute max.

    If images are taking more than a few seconds to download, on any connection, then from my point of view there is something wrong with the web page requirements and/or the image optimisation.
    Last edited by webdev1958; 03-03-2012 at 04:29 AM.

  • #11
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,103
    Thanks
    80
    Thanked 4,554 Times in 4,518 Posts
    I agree with you, but it's a fact of life on his site. I timed one of them. It took 14 seconds to load on my DSL connection. I really don't think it's all the speed of my connection. I think it's partly he is on a really slow server.

    Hmmm...did you read his resume?

    Web Developing
    HTML, CSS, FTP, and basic Adobe Flash CS4


    Basic Photo editing
    Adobe Photoshop CS4, GIMP, Paint.NET, Irfanview

    Given that, he really needs to be aware of such things as id's being unique on a page. And images not being too large.

    A hint for you, Mr. Stroud.
    Last edited by Old Pedant; 03-03-2012 at 04:33 AM.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #12
    Banned
    Join Date
    Apr 2011
    Posts
    656
    Thanks
    14
    Thanked 69 Times in 69 Posts
    Quote Originally Posted by Old Pedant View Post
    .....but it's a fact of life on his site.
    Maybe it is, but I'm just saying from my point of view it doesn't have to be for the reasons I posted earlier.

  • #13
    New Coder
    Join Date
    Nov 2006
    Location
    Washington, DC
    Posts
    30
    Thanks
    3
    Thanked 0 Times in 0 Posts
    Thank you so much for your helps! I know that my JavaScript code is a mess... I just went all over the place and slapped together various scripts to try to tweak it the way I want it to works.

    Ouch, I didn't realize that the images would take so long to load. Guess having such a fast Internet at my dorm messed with the 'feel' of the site loading. I already have a 1024x768 version of all of these images as seen in my flickr account. My screens is 1920x1080 though and I would rather have the picture looking sharp for hd screen too. I'll have to go to the computer lab and compress all of the images right. (reason why I haven't done so is because I don't have photoshop on my computer itself).

    I know that my HTML and CSS is a mess even though I've listed it in my resume. That's just my process. I always make a little mess until I've gotten the site to look the way I want it to and then I'll clean it up each bit at a time to ensure that the site still performs the way I want it to. I know that I should keep it clean at all time but eh...

    I'm not THAT good with HTML and CSS but this site is really more for my marketing class and I intend to make myself better enough over the summer to justify having the resume include these skills. I am using this site to help encourage me to improve my skills so I can start adding to the portfolio and the HTML/CSS/JavaScript/pho is one of those skill set that I really want to improve. Even though I'm working on this site for my marketing class, I fully intend to use this site for real once the semester is over.

    Again, thank you all! I will be looking through the code and try to learn what each bit does.

  • #14
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,103
    Thanks
    80
    Thanked 4,554 Times in 4,518 Posts
    1920x1080 images don't *HAVE* to be too big when using JPEG. Just use a lower quality setting when you save from photoshop.

    You know that it shows you the size the file will be after you choose the JPEG quality, don't you? So just try to find a quality you can live with that keeps the file sizes under, say, 250KB if possible.

    I just experimented with a couple of really big images (6000 by 4000 pixel). I shrank them to 1920x1080 (non proporitional, but this was just for experiment) and both compressed to between 300 and 350 KB using quality 5 in Photoshop. That's lower than I usually use, but the results were reasonable. Good enough I could live with them. Quality 4 produced 240 to 260 KB.
    Last edited by Old Pedant; 03-04-2012 at 07:04 AM.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #15
    Banned
    Join Date
    Apr 2011
    Posts
    656
    Thanks
    14
    Thanked 69 Times in 69 Posts
    I can't see any justification for images weighing in at 300kb.

    For demo purposes, attached is 1920 x 1446px weighing 188kb on my pc after optimising using 95% compression and most of the EXIF data removed. Normally I wouldn't need an image anywhere near this size and most of the "normal" images I have on web pages weigh in anywhere between 20 - 100kb at most.

    ooops...just realised codingforums allows a max size of 50kb for attaching jpg files.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •