WEB Bit of javascript help fixing this code or convert to jquery pls?

Discussion in 'OT Technology' started by Insert Tokens, Dec 23, 2008.

  1. Insert Tokens

    Insert Tokens Making Cancer My Bitch OT Supporter

    Joined:
    Jan 12, 2006
    Messages:
    8,329
    Likes Received:
    75
    Location:
    Tasmania
    Could someone help me make this better?

    I'm setting up a little auto-refreshing webcam at work to monitor traffic for our trucks queuing at the yards..

    There's 6 webcam images on the page.. and I want them all to refresh every minute..

    I've got it going using this:

    Code:
    <script language="JavaScript"><!--
    function refreshIt() {
       if (!document.images) return;
       document.images['image1'].src = 'http://path.to/image1.jpg?' + Math.random();
       document.images['image2'].src = 'http://path.to/image2.jpg?' + Math.random();
       document.images['image3'].src = 'http://path.to/image3.jpg?' + Math.random();
       document.images['image4'].src = 'http://path.to/image4.jpg?' + Math.random();
       document.images['image5'].src = 'http://path.to/image5.jpg?' + Math.random();
       document.images['image6'].src = 'http://path.to/image6.jpg?' + Math.random();
       setTimeout('refreshIt()',60000); // refresh every 60 secs
    }
    //-->
    
    </script>
    <IMG src="http://path.to/spacer.png" height="1" width="1" onload="refreshIt()">
    
    <img src="http://path.to/image1.jpg" name="image1" />
    <img src="http://path.to/image2.jpg" name="image2" />
    <img src="http://path.to/image3.jpg" name="image3" />
    <img src="http://path.to/image4.jpg" name="image4" />
    <img src="http://path.to/image5.jpg" name="image5" />
    <img src="http://path.to/image6.jpg" name="image6" />
    
    Is there a simpler way I can change the javascript to just reload the source of any image with 'x' name, rather than the javascript having to have the source of each image defined?

    Eg i'd have:

    <img src="http://path.to/image1.jpg" name="cam-image" />
    <img src="http://path.to/image2.jpg" name="cam-image" />
    <img src="http://path.to/image3.jpg" name="cam-image" />

    Then the javascript just grabs all images off a page with the name "cam-image" and turns them into an array, then refreshes all images in that array?

    Example (I know this doesn't work, but i'm hoping it makes it clear what i'm after).. image.path is somehow grabbed from the source, and cam-image is an array:

    Code:
    <script language="JavaScript"><!--
    function refreshIt() {
       if (!document.images) return;
       document.images['cam-image'].src = image.path + Math.random();
       setTimeout('refreshIt()',60000); // refresh every 60 secs
    }
    //-->
    </script>
    
    Or -any- better way of refreshing 6 images on a page every minute :hsd:

    Will consider paypal reward if solution is in jquery :x:
     
  2. 95vr4

    95vr4 OT Supporter

    Joined:
    Oct 6, 2004
    Messages:
    2,513
    Likes Received:
    0
    Location:
    Weddington, NC
    Not sure about jQuery, but I know prototype has a periodical ajax update function which I've used before. It's a piece of cake to implement too

    all it takes
    Code:
    new Ajax.PeriodicalUpdater('items', '/items/ajax.php', {
      method: 'get', frequency: 60, decay: 0
    });
    
     
  3. 95vr4

    95vr4 OT Supporter

    Joined:
    Oct 6, 2004
    Messages:
    2,513
    Likes Received:
    0
    Location:
    Weddington, NC
    You could put this in a file (we'll say /items/ajax.php to go along with the example) that's loaded by ajax,
    Code:
    <IMG src="http://path.to/spacer.png" height="1" width="1" onload="refreshIt()">
    
    <img src="http://path.to/image1.jpg" name="image1" />
    <img src="http://path.to/image2.jpg" name="image2" />
    <img src="http://path.to/image3.jpg" name="image3" />
    <img src="http://path.to/image4.jpg" name="image4" />
    <img src="http://path.to/image5.jpg" name="image5" />
    <img src="http://path.to/image6.jpg" name="image6" />
    
    Then put a div 'items' in the main page.

    Code:
    <div id='items'>...Loading...</div>
    
    new Ajax.PeriodicalUpdater('items', '/items/ajax.php', {
      method: 'get', frequency: 60, decay: 0
    });
    
     
    If you want to get real fancy u can make an ajax loading gif during the ajax calls :hsd:
     
  4. Ender0910

    Ender0910 woot!

    Joined:
    Jun 1, 2004
    Messages:
    3,039
    Likes Received:
    0
    Location:
    Redmond/Bay Area
    Code:
    <html>
    <head>
    <script src="jquery-1.2.6.min.js"></script>
    
    <script>
    
     $(document).ready(function() {
    
        refreshAll();
    
     });
    
     function refreshAll(){
    
        $(".refreshMe").attr("src", 
                   function(){
                        return $(this).attr("baseSrc")+"?"+ Math.random()
                    });
    
        setTimeout("refreshAll()", 1000);
    
     }
    </script>
    </head>
    
    <body>
    
    <img src="" class="refreshMe" baseSrc="http://path.to/image1.jpg">
    <img src="" class="refreshMe" baseSrc="http://path.to/image2.jpg">
    
    </body>
    </html>
    
    Basically made a custom attribute called baseSrc. jQuery periodically grabs all images with the class "refreshMe" and sets the source of that image to baseSrc + random.

    I love jQuery :bowdown:

    edit: although I guess the concept you were looking for were the custom attributes (not sure what they're really called) and that's not really jQuery specific.
     
    Last edited: Dec 23, 2008
  5. TheDarkHorizon

    TheDarkHorizon \xC0\xFF\xEE

    Joined:
    Sep 26, 2002
    Messages:
    2,396
    Likes Received:
    0
    Location:
    San Francisco, CA
    Code:
    <html>
      <head>
        <style type="text/css">
          .image-refresh {
            padding: 5px;
            margin: 5px;
            border: 1px solid #000;
            float: left;
          }
        </style>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
        <script type="text/javascript">
          var ImageRefreshConfig = {
            /**
             * interval: Time in seconds between image reloads.
             */
            interval:  60,
            /**
             * classname: Class of images to refresh.
             */
            classname:  'image-refresh'
          };
    
          $(document).ready(function() {
            var iId = setInterval(function() {
              $('img.' + ImageRefreshConfig.classname).attr('src', function(u) {
                var sep = (this.origsrc.indexOf('?') == -1) ? '?' : '&';
                if(typeof this.origsrc == 'undefined') {
                  this.origsrc = this.src;
                }
                return this.origsrc + sep + (new Date()).getTime();
              });
            }, 1000*ImageRefreshConfig.interval);
          });
        </script>
      </head>
      <body>
        <img src="http://path.to/image1.jpg" class="image-refresh">
        <img src="http://path.to/image2.jpg" class="image-refresh">
        <img src="http://path.to/image3.jpg" class="image-refresh">
        <img src="http://path.to/image4.jpg" class="image-refresh">
      </body>
    </html>
    
    I haven't used jQuery much, but this works. Tested in IE6/Opera/Firefox 3/Safari 3.
     
  6. TheDarkHorizon

    TheDarkHorizon \xC0\xFF\xEE

    Joined:
    Sep 26, 2002
    Messages:
    2,396
    Likes Received:
    0
    Location:
    San Francisco, CA
    This works, but it doesn't degrade gracefully for browsers with JavaScript disabled. Otherwise, it's similar to the code I just posted. :h5:
     
  7. Ender0910

    Ender0910 woot!

    Joined:
    Jun 1, 2004
    Messages:
    3,039
    Likes Received:
    0
    Location:
    Redmond/Bay Area
    true. I guess he could populate the src= to begin with as well and slam a meta refresh in there under <noscript> tags.

    actually... does <noscript> work in the <head> section?

    Also, I saw that IE complains about activeX something when you use it for the first time. But since this is an internal tool hopefully it doesn't matter :hs:
     
  8. Insert Tokens

    Insert Tokens Making Cancer My Bitch OT Supporter

    Joined:
    Jan 12, 2006
    Messages:
    8,329
    Likes Received:
    75
    Location:
    Tasmania
    Thanks for those solutions guys.. really appreciate the quick help.

    TheDarkHorizon, I get a javascript error with your solution saying "Error: 'this.origsrc' is null or not an object".. but I like that yours refreshes the src itself rather than needing a second baseSrc tag..

    Is there a reason I can't just do this (going off your code Ender0910):

    Code:
    <script>
     $(document).ready(function() {
        refreshAll();
     });
     function refreshAll(){
        $(".refreshMe").attr("src", 
                   function(){
                        return $(this).attr("src")+"?"+ Math.random()
                    });
        setTimeout("refreshAll()", 1000);
     }
    </script>
    
        <img src="http://path.to/image1.jpg" class="refreshMe">
        <img src="http://path.to/image2.jpg" class="refreshMe">
    
    It seems to work fine when I test it..
     
  9. Ender0910

    Ender0910 woot!

    Joined:
    Jun 1, 2004
    Messages:
    3,039
    Likes Received:
    0
    Location:
    Redmond/Bay Area
    It'll work. DarkHorizon and I were just discussing some corner cases (browser compatibility and disabled javascript). But in most situations it should do fine, especially since this is a tool for your own use.
     
  10. Insert Tokens

    Insert Tokens Making Cancer My Bitch OT Supporter

    Joined:
    Jan 12, 2006
    Messages:
    8,329
    Likes Received:
    75
    Location:
    Tasmania
    It'll be public in a sense, on our website for the trucking companies to use, but they're already pretty much locked in to using IE6 (slowly all moving to IE7) + javascript turned on for our booking system, so it helps knowing we have those guidelines to work with and don't have to worry about random browsers or no js.

    The reason we don't want to use a meta-refresh is because we're upgrading the cameras soon to take shots every second or 2 for real-time updates, and reloading the entire page every second would be too heavy on our servers.. but having it inside the <noscript> tag is a good idea just to catch those very very few people who might have js turned off.. so i'll play with that too.

    PM me your paypals and i'll throw $20 each to you for your help :)
     
  11. Ender0910

    Ender0910 woot!

    Joined:
    Jun 1, 2004
    Messages:
    3,039
    Likes Received:
    0
    Location:
    Redmond/Bay Area
    oh! I just noticed what you did there with the code snippet. I didn't see it in my first reply.

    You're using the src attribute instead of baseSrc. Well, I'm not 100% sure if it'll work well since from the looks of it it might constantly tack on ?random to the previous src

    making it image?random?random?random.... etc. and eventually hit the URL request string limit (1024 on IE6 I believe? maybe 2048). At this point, the URLs will stop being unique and might have refresh issues.

    What you can do is add some "?" detection code in the same vein that DarkHorizon has and strip out the ?random before you tack on the new ?random

    hope that makes sense...
     
  12. Insert Tokens

    Insert Tokens Making Cancer My Bitch OT Supporter

    Joined:
    Jan 12, 2006
    Messages:
    8,329
    Likes Received:
    75
    Location:
    Tasmania
    Ah gotcha.. damn.. so obvious yet I somehow missed that. You're absolutely right too, it does do that.

    So I guess I have to either get TheDarkHorizon's working or just go through adding baseSrc's to them..
     
  13. Ender0910

    Ender0910 woot!

    Joined:
    Jun 1, 2004
    Messages:
    3,039
    Likes Received:
    0
    Location:
    Redmond/Bay Area
    Code:
    <script>
    
     $(document).ready(function() {
        refreshAll();
     });
    
     function refreshAll(){
    
        $(".refreshMe").attr("src", 
                   function(){
    
                     var src = $(this).attr("src");
                     var baseSrc = src;
    
                     if(src.indexOf('?') > 0){
                         baseSrc = src.substring(0, src.indexOf('?'));
                     }
    
                      return baseSrc +"?"+ Math.random()
                    });
    
        setTimeout("refreshAll()", 1000);
    
     }
    </script>
    
        <img src="http://path.to/image1.jpg" class="refreshMe">
        <img src="http://path.to/image2.jpg" class="refreshMe">
    
    
    here's what I was talking about. basically clears out the the ? and anything after it.
     
  14. Insert Tokens

    Insert Tokens Making Cancer My Bitch OT Supporter

    Joined:
    Jan 12, 2006
    Messages:
    8,329
    Likes Received:
    75
    Location:
    Tasmania
    Ah you champion.. that works perfectly :)

    Time for me to head home now, but thanks heaps for your help.. PM me your paypal and i'll throw some cash your way when I get home..
     

Share This Page