www.webdeveloper.com
Results 1 to 15 of 15

Thread: Need a clever mind!

  1. #1
    Join Date
    Nov 2011
    Posts
    6

    Question Need a clever mind!

    Hi everybody,

    I'm very new to this, so forgive me if i'm being a bit dense.

    I'm using a script that randomly redirects to a page after a certain amount of time. This works great, but how do can I stop it from redirecting to a page more than once. Basically, I don't want it to repeat any pages (a tleast until it's been through them all once).

    Sorry, if i'm not very clear - my brain's a bit frazzled at the moment!

    This is the script:






    <script type="text/javascript">
    <!--
    Array.prototype.random = function () {return this[Math.floor(Math.random() * this.length)]}

    Date.ONE_SECOND = 1000;

    url =
    ['page3.html',
    'page4.html',
    'page5.html',
    'page6.html',
    'page7.html',
    'page8.html',]

    setTimeout('location = url.random()', 30 * Date.ONE_SECOND)
    // -->
    </script>

  2. #2
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,373
    I would suggest saving your pages in a cookie.
    Then every time you reload the program, read the next cookie
    until there are no more and then reload the cookie with
    the next sequence of redirects.

  3. #3
    Join Date
    Mar 2007
    Location
    U.K.
    Posts
    1,127
    Quote Originally Posted by Tofana View Post

    I'm using a script that randomly redirects to a page after a certain amount of time. This works great, but how do can I stop it from redirecting to a page more than once. Basically, I don't want it to repeat any pages (a tleast until it's been through them all once).
    Just substitute your own filenames in the array passed to the function. You can have any number of filenames.

    Code:
    <script type='text/javascript'>
    
    function Randpage( pageSet, cookieName, secs ) /* Redirect to random page with no repetition until set exhausted */
    {
      function setCookie( cName, cValue, daysLife )
      {
        var dt = new Date(), 
            life = daysLife || 0, 
            expSecs = ( expSecs = life.toString().match( /\bsecs\s*=\s*(\d+)/i ) ) ? Number( expSecs[ 1 ] ) : 0,
            params = ( life ? ( ";expires=" + new Date( expSecs ? ( dt.setTime( dt.getTime() + expSecs * 1000 ) )                                                          : ( dt.setDate( dt.getDate() + life) ) ).toUTCString() ) : "" );
        
        document.cookie = cName + "=" + encodeURIComponent( cValue ) + params;
        
        return readCookie( cName );
      } 
    
      function readCookie( cName )
      {
        var v;
    
        return decodeURIComponent( ( v = ( document.cookie || "" ).match( "(^|\\s)" + cName + "=([^;$]+)" ) ) ? v[ 2 ] : "" );
      }
      
      (function( /*2843294C6F676963416C69*/ )
      {
        var bits = readCookie( cookieName ),
            idx;   
          
        if( bits.length != pageSet.length || /[^10]/.test( bits ) || bits.indexOf( '0' ) == -1 )
          for( bits = "", i = 0; i < pageSet.length; i++ )
            bits += '0';
         
        while( bits.charAt( idx = Math.floor( Math.random() * bits.length ) ) == 1 )
        ;
        
        bits = bits.substring( 0, idx ) + '1' + bits.substring( idx + 1 );
        
        setCookie( cookieName, bits, 30 );
            
        setTimeout( function(){ location.href = pageSet[ idx ]; }, secs * 1000 );        
        
      })();    
    }
    
    Randpage( [ 'page1.html', 'page2.html', 'page3.html', 'page4.html', 'page5.html' ], 'randPage', 1 );
    
    </script>
    Where used, return should be executed unconditionally and always as the last statement in the function.

    That's my signature, it's not part of the damn post!

  4. #4
    Join Date
    Nov 2011
    Posts
    6
    Thanks for the response guys, I really appreciate it.

    Still a bit confused though. Logic Ali, i'm a bit unsure as to which parts of the script I need to alter. When you say "substitute your own filenames in the array passed to the function" i'm not really sure what you mean?

    Sorry for being slow, this is all a bit double-dutch to me at the minute!

  5. #5
    Join Date
    Mar 2007
    Location
    U.K.
    Posts
    1,127
    Quote Originally Posted by Tofana View Post
    Thanks for the response guys, I really appreciate it.

    Still a bit confused though. Logic Ali, i'm a bit unsure as to which parts of the script I need to alter. When you say "substitute your own filenames in the array passed to the function" i'm not really sure what you mean?

    Sorry for being slow, this is all a bit double-dutch to me at the minute!
    Code:
    Randpage( [ 'page1.html', 'page2.html', 'page3.html', 'page4.html', 'page5.html' ], 'randPage', 1 );
    Substitute the names in green for your own filenames. Keep the syntax exactly the same. Commas between quoted filenames except after the last one. If it doesn't work, check the error console for error messages relating to your page.
    Where used, return should be executed unconditionally and always as the last statement in the function.

    That's my signature, it's not part of the damn post!

  6. #6
    Join Date
    Nov 2011
    Posts
    6
    Thanks a lot! I'll give it a go later. Really appreciate your time.

  7. #7
    Join Date
    Nov 2011
    Posts
    6
    I've replaced my old script with the one you've kindly provided. It works really well for the auto-redirect and randomising of the pages, but still seems to repeat pages. Do I need a seperate code to create the required cookies or is that already in the script? It's probably glaringly obvious, but I can't seem to see it!

  8. #8
    Join Date
    Mar 2007
    Location
    U.K.
    Posts
    1,127
    Quote Originally Posted by Tofana View Post
    I've replaced my old script with the one you've kindly provided. It works really well for the auto-redirect and randomising of the pages, but still seems to repeat pages. Do I need a seperate code to create the required cookies or is that already in the script? It's probably glaringly obvious, but I can't seem to see it!
    All the cookie handling is being done. I realised that the same page could appear consecutively at one point in the cycle, which is now fixed. Just replace this function with the one you have but keep the function call that you're using.
    If it still doesn't work as expected, post a live URL.

    Code:
    function Randpage( pageSet, cookieName, secs ) /* Redirect to random page with no repetition until set exhausted */
    {
      function setCookie( cName, cValue, daysLife )
      {
        var dt = new Date(), 
            life = daysLife || 0, 
            expSecs = ( expSecs = life.toString().match( /\bsecs\s*=\s*(\d+)/i ) ) ? Number( expSecs[ 1 ] ) : 0,
            params = ( life ? ( ";expires=" + new Date( expSecs ? ( dt.setTime( dt.getTime() + expSecs * 1000 ) )                                                          : ( dt.setDate( dt.getDate() + life) ) ).toUTCString() ) : "" );
        
          document.cookie = cName + "=" + encodeURIComponent( cValue ) + params;
        
          return readCookie( cName );
      } 
    
      function readCookie( cName )
      {
        var v;
    
        return decodeURIComponent( ( v = ( document.cookie || "" ).match( "(^|\\s)" + cName + "=([^;$]+)" ) ) ? v[ 2 ] : "" );
      }
      
      (function( /*2843294C6F676963416C69*/ )
      {
        var bits = readCookie( cookieName ),
            idx = -1,
            zeros,
            last = false;   
            
        if( bits.length != pageSet.length || /[^10]/.test( bits ) /*|| bits.indexOf( '0' ) == -1*/ || ((zeros=bits.match(/0/g)) && ( last = (zeros.length == 1 ) ) ) )
        {
          if( last )
            idx = bits.indexOf( '0' );
          
          for( bits = "", i = 0; i < pageSet.length; i++ )
            bits += ( last && idx == i ? '1' : '0' );
        }
         
        if( idx == -1 )
          while( bits.charAt( idx = Math.floor( Math.random() * bits.length ) ) == 1 )
          ;
        
        bits = bits.substring( 0, idx ) + '1' + bits.substring( idx + 1 );
        
        setCookie( cookieName, bits, 30 );
            
        setTimeout( function(){ location.href = pageSet[ idx ]; }, secs * 1000 );        
        
      })();    
    }
    Where used, return should be executed unconditionally and always as the last statement in the function.

    That's my signature, it's not part of the damn post!

  9. #9
    Join Date
    Nov 2011
    Posts
    6
    Hi Logic Ali,

    Thanks very much for your help, and apologies for the delay. I’ve only just got round to getting a proper test online. Unfortunately the pages still seem to be repeating.

    Here’s the url: http://www.thedpc.co.uk/

    There’s 5 pages and they change every 5 seconds.

    Any clues?

  10. #10
    Join Date
    Mar 2007
    Location
    U.K.
    Posts
    1,127
    Quote Originally Posted by Tofana View Post
    Hi Logic Ali,

    Thanks very much for your help, and apologies for the delay. Iíve only just got round to getting a proper test online. Unfortunately the pages still seem to be repeating.
    That is not the way I envisaged the code to be used. I thought you were going to use the script on just one landing page from which you perform a single redirect. The script isn't designed to consider the page it's on as one of the series.
    Where used, return should be executed unconditionally and always as the last statement in the function.

    That's my signature, it's not part of the damn post!

  11. #11
    Join Date
    Mar 2005
    Location
    Behind you...
    Posts
    862
    My initial thought to the problem was AJAX. I read through the topic just to see how things were going; my thought now is AJAX.

    Given the simplicity of the pages, it would be best to just use a simple AJAX function to load a random page. You could easily store the previously loaded pages in an array and thus quickly and easily check if a page has already been loaded.

    Something like I wrote below would let you set an array of pages to load randomly. No pages that have been previously loaded will be loaded a second time. Once all of the pages have been loaded the function will just exit.

    Since you'd be calling this from some interval, you could simply add in a line of code to cancel the timeout once it reaches the limit as well to prevent a useless loop.
    Code:
    var prev_pages = new Array();
    var list_pages = new Array("page1.html", "page2.html", "page3.html", "page4.html", "page5.html");
    
    function setAjaxObj()
    {
      var nAjax;
      if(window.XMLHttpRequest)
      {
        nAjax = new XMLHttpRequest();
      } else {
        nAjax = new ActiveXObject("Microsoft.XMLHTTP");
      }
      return nAjax;
    }
    
    function ajax_random_page()
    {
      if(prev_pages.length == list_pages.length)
      {
        return;
      }
      var rnd_number = 1;
      var rnd_page = "page"+rnd_number+".html";
    
      while(list_pages.indexOf(rnd_page) > -1) {
        rnd_number = Math.round(Math.random()*list_pages.length-1);
        rnd_page = "page"+rnd_number+".html";
      }
    
      prev_pages[prev_pages.length] = rnd_page;
    
      var xmlhttp = setAjaxObj();
    
      if(xmlhttp)
      {
        xmlhttp.onreadystatechange=function()
        {
          if(xmlhttp.readyState == 4)
          {
            document.body.innerHTML = xmlhttp.responseText;
          }
        }
    
        xmlhttp.open("GET", rnd_page);
        xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xmlhttp.setRequestHeader("Connection", "close");
        xmlhttp.send(null);
      }
    }
    "Given billions of tries, could a spilled bottle of ink ever fall into the words of Shakespeare?"

  12. #12
    Join Date
    Jan 2009
    Location
    Insanity
    Posts
    1,131
    I will add that you need to consider on aspect of this code and that is the time between the timer and the page load.

    I suggest that you only start your counter timer when the page has loaded, what I just experienced was a random set of pages that were not displayed for 5 seconds, the shortest period was 1 second and that because of the lag between page and image, this is due to the ISP that I have who is over subscribed and the connection I have on my dongle is slow.
    We all have baggage to carry in life, unfortunately for me I always get the trolley with the wonky wheel...
    Code:
    Youre = {
          STILL_not_getting_it:function(){
               alert("YOU, the original poster / thread starter NEED to POST the code and NOT a LINK.");
          },
          MissingThePoint:function(msg){
                alert("You're missing the point. " + msg);
          }
    }
    Youre.STILL_not_getting_it();

  13. #13
    Join Date
    Mar 2005
    Location
    Behind you...
    Posts
    862
    JunkMale brings up an excellent point. Viewing the page myself it was rather annoying due to the additional waiting period(s).

    In my example code(after the xmlhttp.readyState == 4 part) you could always add in a little timer code using setInterval(). Something like
    Code:
    ...
    if(xmlhttp.readyState == 4)
          {
            document.body.innerHTML = xmlhttp.responseText;
            my_interval = setInterval("ajax_random_page()", 5000);
          }
    ...
    And just simply make sure to declare 'my_interval' as a global var(at the top with the arrays), just in the event you need to cancel the timer.

    The other solution to that problem would be something I wouldn't necessarily recommend, but would get the job done and as long as the pages loaded are as simple as your example seems to make them, wouldn't be all that bad. You could simply create a 'buffer' or pre-load function which cycles through the entire list of pages and saves them as variables which you can more quickly call upon later, removing any latency between page loads.
    "Given billions of tries, could a spilled bottle of ink ever fall into the words of Shakespeare?"

  14. #14
    Join Date
    Nov 2011
    Posts
    6
    Hey guys, thanks for your response!

    How do I go about implementing this? Do I need to add or alter any parts? Such as the time out code, or it already there? I’ve replaced the code with the ajax one, but it doesn’t seem to be working at the moment. Apologies for asking what are probably really obvious questions – I’m learning as I go along!

    The slow-loading of it has been my worry as well. It’s on a free webhost at the moment, so I guess that can’t be helping either.

    Thanks guys, really appreciate your time.

  15. #15
    Join Date
    Mar 2005
    Location
    Behind you...
    Posts
    862
    There are several ways you could go about this. What I would consider to be one of the better ones would include pre-loading the pages to be used so that all users experience the same thing once the script is ready and starts.

    File set up:
    You'll want to slightly change the way your files are set up on the server first. The changes are relatively minor and once you are done it would make any further additions pretty easy to add. You will want an .index.html page in the root directory. This page will consist of the 'full code' I'll show at the end of this post. The rest of the files will be your pages(which will be included in your page array). The contents of these pages will be pretty simple; something like I have below:
    Code:
    <div style="background: url('wpimages/wp8fca4114.jpg'); background-position: top center; background-attachment: scroll; color: #000000; text-align: center; width: 100%; height: 1000px;">
    <div style="text-align: left; margin: auto; position: relative; width: 750px; height: 1000px;">
      <div id="txt_1_C01" style="position: absolute; left: 282px; top: 261px; width: 249px; height: 334px;">
        <div class="Body-P">
            <span class="Body-C">1</span>
        </div>
      </div>
      <div style="position: absolute; left: 161px; top: 43px; width: 491px; height: 153px;">
        <div id="frag_9" style="text-align:left;">
        
        </div>
      </div>
    </div>
    </div>
    You would of course substitute the background images or whatever other code you needed in each of these files and name them accordingly(page1.html, page2.html, etc).


    Main index.html
    Once you have all of the extra files(pages) set up then you only need to set up the index.html so that it loads each of these 5 pages(in random order, never repeating the same page). You can do this using the code I outlined in my earlier posts but there are a few modifications you need. In your website's current source the function I wrote is never called and so nothing would happen. So we'll want to use the body's 'onload' event to start our scripts. This will call a pre-loading function I just wrote that will load all of the pages in the array and store them in a corresponding array to be called later. This will remove load times between pages and should remove any potential latency while experiencing the site in action. The last thing is simply that once the pre-load function has completed, it will call my original function which will randomly load a page then start a setTimeout() function that will wait 5 seconds before re-running this function once more to load another page. Once all the pages have been loaded it will simply exit and the script stops.
    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html lang="en">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="Generator" content="Serif WebPlus Starter Edition   (2.0.1.11)">
    <title>Home</title>
    <script type='text/javascript'>
    
    var prev_pages = new Array();
    var list_pages = new Array("index.html", "page2.html", "page3.html", "page4.html", "page5.html");
    var page_data = new Array();
    var cur_page = 1;
    
    function setAjaxObj()
    {
      var nAjax;
      if(window.XMLHttpRequest)
      {
        nAjax = new XMLHttpRequest();
      } else {
        nAjax = new ActiveXObject("Microsoft.XMLHTTP");
      }
      return nAjax;
    }
    
    function ajax_preload_page()
    {
      if(cur_page < list_pages.length)
      {
        var xmlhttp = setAjaxObj();
    
        if(xmlhttp)
        {
          document.body.innerHTML = "Loading page " + cur_page + " of " + list_pages.length;
          get_page = "page" + cur_page + ".html";
    
          xmlhttp.onreadystatechange=function()
          {
            if(xmlhttp.readyState == 4)
            {
              page_data[cur_page] = xmlhttp.responseText;
              cur_page++;
              ajax_preload_page();
            }
          }
    
          xmlhttp.open("GET", get_page);
          xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
          xmlhttp.setRequestHeader("Connection", "close");
          xmlhttp.send(null);
        }
      } else {
        random_page();
      }
    }
    
    function random_page()
    {
      if(prev_pages.length == list_pages.length)
      {
        return;
      }
      var rnd_number = 1;
      var rnd_page = "page" + rnd_number + ".html";
    
      while(prev_pages.indexOf(rnd_page) > -1) {
        rnd_number = Math.round(Math.random()*list_pages.length-1);
        rnd_page = "page" + rnd_number + ".html";
      }
    
      prev_pages[prev_pages.length] = rnd_page;
    
      document.body.innerHTML = page_data[rnd_number];
      setInterval("random_page()", 5000);
    }
    
    </script>
    <style type="text/css">
    <!--
    body {margin: 0px; padding: 0px;}
    a:link {color: #2c3651;}
    a:visited {color: #1f5b8b;}
    a:hover {color: #2c3651;}
    a:active {color: #2c3651;}
    .Body-P
            {
            margin:0.0px 0.0px 12.0px 0.0px; text-align:left; font-weight:400; 
            }
    .Body-C
            {
            font-family:"Trebuchet MS", sans-serif; font-size:267.0px; 
            line-height:1.16em; 
            }
    -->
    </style>
    </head>
    
    <body onload="ajax_preload_page()">
    
    </body>
    </html>
    It's all simple coding that you can change up if you'd like. The pre-loading script just displays a simple message to indicate progress. Once it has gotten all of the pages in your array it will then start displaying a random page every 5 seconds until all pages have been displayed.
    "Given billions of tries, could a spilled bottle of ink ever fall into the words of Shakespeare?"

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

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



Recent Articles