Page 1 of 2 12 LastLast
Results 1 to 10 of 17

Thread: Looping Sequential function in javascript?

  1. #1
    Join Date
    Sep 2008
    Posts
    119
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Question Looping Sequential function in javascript?

    Ok,

    So I have 3 elements...

    with the ids = "c1","c2", and "c3".


    What I am trying to do, is create a javascript function that loops through each element sequentially.

    I don't mean a "for i", type loop, but I mean if I click a button, I get an alert that says "c1 = first element", but if I click that same button 15 minutes later, it says "c2 - second element", but after "c3" is alerted, it loops back to "c1".

    Similar to a carousel slideshow that loops.......

    http://sorgalla.com/projects/jcarous..._circular.html

    but with elements...

    hmm...

    I'll try some more and see if I can get this.

    Code:
    <script>
    function getcrawling()
    {
    // Begin crawling element	
    divcrawl = document.getElementById('cont');
    acrawl = divcrawl.getElementsByTagName("a");
    var a_array = new Array();
    for (j=0;j<acrawl.length;j++)
    {
    a_array[j] = acrawl[j].id;
    splitstring = document.getElementById(acrawl[j].id).id.split("-");
    if (splitstring[1] == 'one'){document.getElementById(acrawl[j].id).id = splitstring[0] + '-two';}
    else if (splitstring[1] == 'two'){document.getElementById(acrawl[j].id).id = splitstring[0] + '-three';}
    else if (splitstring[1] == 'three'){document.getElementById(acrawl[j].id).id = splitstring[0] + '-four';}
    else if (splitstring[1] == 'four'){document.getElementById(acrawl[j].id).id = splitstring[0] + '-one';}
    else {document.getElementById(acrawl[j].id).id = splitstring[0] + '-two';}
    }
    alert(a_array);
    }
    </script>
    
    <div id="cont" name="cont">
    <a id="345" >test</a><br />
    <a id="335" >test</a><br />
    <a id="342" >test</a><br />
    <a id="335" >test</a><br />
    <a id="325" >test</a><br />
    <a id="322" >test</a><br />
    <a id="315" >test</a><br />
    <a id="385" >test</a><br />
    <a id="382" >test</a><br />
    </div>
    <br><br>
    <a onclick="getcrawling();">test crawl</a>
    Ok, So I got it working using a loop based crawler. This is ugly, but I am still getting used to decoding the moderators heiroglyphs.
    Last edited by Falkon303; 02-22-2009 at 10:32 AM.
    document.write is document.wrong

  2. #2
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,876
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    Code:
    <script type="text/javascript">
      var nextEl = (function(n) {
        var ordinals = {
          '1' : 'first',
          '2' : 'second',
          '3' : 'third'
        };
    
        var i = 1;
    
        function nextEl() {
          alert("c" + i + " - " + ordinals[i] + " element");
          i = ((i + 1) % n) + 1;
        }
    
        return nextEl;
      })(3);
    </script>
    
    <input type="button" onclick="nextEl();">
    What you've got is not a 'crawler' of any kind — that is a misnomer. Additionally, why are all your variables global? Not to mention that your HTML is entirely invalid.
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends français | entiendo español | tôi ít hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

  3. #3
    Join Date
    Sep 2008
    Posts
    119
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default

    I would like to know why global variables are bad.

    I appreciate the notification that my html is invalid, but when I stated already that is was (I said "This is ugly."), that doesn't make much sense to restate the obvious.
    document.write is document.wrong

  4. #4
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,876
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    I appreciate the notification that my html is invalid, but when I stated already that is was (I said "This is ugly."), that doesn't make much sense to restate the obvious.
    There's a difference between 'ugly' (works, but in a nasty way — e.g. using a whole bunch of global variables) and 'broken' (isn't even real HTML).

    Rather than write a whole essay on global variables and why they're bad, I'll point you to this one: http://c2.com/cgi/wiki?GlobalVariablesAreBad

    Alternatives in JS include using closures (as above) or sticking them in namespacing objects (or a combination of both).

    There are some more examples of efficient management of scope in in JS in this thread. My last post in that thread deals specifically with the issues of globals, too.
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends français | entiendo español | tôi ít hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

  5. #5
    Join Date
    Sep 2008
    Posts
    119
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default

    I appreciate your response. If you could let me know what exactly is broken in my html in particular, it would help me to better understand. I realize I didn't include my dtd, head tags, etc....

    What are Local and Global variables?
    When a function is defined certain variables used for storing values are incorporated inside the function. These variables are found and used only inside these functions. Since functions are separate from the main code, it's advisable to use variables that are initialized only when a function is called and die when the execution comes out of the function. Variables that exist only inside a function are called Local variables. They have no presence outside the function.

    So, if I use "function(value);" rather than attaching a function handler onto the element itself, that is an example of using globals vs locals?
    document.write is document.wrong

  6. #6
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,876
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    I realize I didn't include my dtd, head tags, etc....
    Well, that certainly does make it rather broken, but I did assume it to be a code fragment

    <script> requires an attribute type="text/javascript"; <br /> has dodgy pseudo-XHTML syntax, which isn't used on your later <br>s, and your use of <br>s here is presentational rather than semantic, so it shouldn't really happen. Try wrapping your links in some other element. An <ul> would seem to suit this situation.

    If you have any doubts about your HTML in future, the validator can usually sort them out (but it will miss some things; it can't tell the difference between semantic and presentational use of an element, for example). It can even handle code snippets. You should be aiming at HTML 4.01 Strict.
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends français | entiendo español | tôi ít hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

  7. #7
    Join Date
    Sep 2008
    Posts
    119
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default

    hahahah! You know it's funny. Every time I code I attach the type="text/javascript", but this was after 1 day w/no sleep (too much coffee) and I was exhausted.

    as for the <br /> dreamweaver generated those entirely on her own. My only excuse there is being too lazy to battle a program. Thanx for the tips though.
    document.write is document.wrong

  8. #8
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,876
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    Oh, I missed responding to this:

    So, if I use "function(value);" rather than attaching a function handler onto the element itself, that is an example of using globals vs locals?
    No. You're not creating any variable there at all.

    as for the <br /> dreamweaver generated those entirely on her own. My only excuse there is being too lazy to battle a program.
    Maybe it's time you got an editor that you don't have to fight in order to get what you want, then.
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends français | entiendo español | tôi ít hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

  9. #9
    Join Date
    Sep 2008
    Posts
    119
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default

    Quote Originally Posted by Twey View Post
    Code:
    <script type="text/javascript">
      var nextEl = (function(n) {
        var ordinals = {
          '1' : 'first',
          '2' : 'second',
          '3' : 'third'
        };
    
        var i = 1;
    
        function nextEl() {
          alert("c" + i + " - " + ordinals[i] + " element");
          i = ((i + 1) % n) + 1;
        }
    
        return nextEl;
      })(3);
    </script>
    
    <input type="button" onclick="nextEl();">
    What you've got is not a 'crawler' of any kind — that is a misnomer. Additionally, why are all your variables global? Not to mention that your HTML is entirely invalid.
    Your script subtracts instead of increments, but that's ok. Same loop really. Thanx Twey, I'll study this. How would I make this go to 5 or 6?

    Update:

    I made some modifications to your script to set a limit number using an if statement, this increments instead of decrements(?).

    Code:
    <script type="text/javascript">
      var nextEl = (function(n) {
        var ordinals = {
          '1' : 'first',
          '2' : 'second',
          '3' : 'third',
    	  '4' : 'fourth'
        };
        var i = 1;
        function nextEl() {
          alert("c" + i + " - " + ordinals[i] + " element");
    	  if (i == '4') 
    	  {i = 1;} else {i = (i + 1);}
        }
        return nextEl;
      })(3);
    </script>
    <input type="button" onClick="nextEl();">
    I think it would also be cool to be able to set the limit to the length of an element in a page. For example if there are 54 "a" elements, this function could go through each one by one, and start at the beginning when it reached the end. Thanx much for help on this Twey.

    is there anyway to use (if ordinals[i] == undefined), to represent the end of the list. This would be perfect for having an unlimited amount of items in the array, but the script itself would know the end.
    *grovels at your mod feet*
    Last edited by Falkon303; 02-24-2009 at 08:51 PM.
    document.write is document.wrong

  10. #10
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,876
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    Ah, yes, adding 1 to it throws it right off, since it ends up on 3 which should never happen. That'll teach me to show off by breaking KISS
    Code:
    <script type="text/javascript">
      var nextEl = (function(n) {
        var ordinals = {
          '1' : 'first',
          '2' : 'second',
          '3' : 'third'
        };
    
        var i = 1;
    
        function nextEl() {
          alert("c" + i + " - " + ordinals[i] + " element");
          i = i > n ? 1 : i + 1;
        }
    
        return nextEl;
      })(3);
    </script>
    You can make it do more by increasing the 3 at the bottom.

    Anyway, yes, the maths I used to try to get it to cycle isn't really important (maths has never been my strong point ) and you can do it with an if as you attempted (the above being a condensed, less redundant version of such):

    Code:
        function nextEl() {
          alert("c" + i + " - " + ordinals[i] + " element");
    
          if (i > n)
            i = 1
          else
            ++i;
        }
    The strange behaviour you encountered was because you wrapped your numbers in quotation marks, making them into strings. 1 + 1 === 2, but '1' + '1' === '11'.
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends français | entiendo español | tôi ít hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

Bookmarks

Posting Permissions

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