SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Wizard Zaggs's Avatar
    Join Date
    Feb 2005
    Posts
    1,048
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    javascript clone question

    Hi Guys,

    I wrote this bit of code to "clone" a block of html:

    Code:
    <!--
    function copyTrue(){
    var t = document.getElementById('roomdiv').cloneNode(true);
    document.getElementById('test1').appendChild(t);
    return true;
    }
    //-->
    I trigger the function from a link, like so:

    Code:
    <a href="#" onClick="copyTrue()">Click here</a>
    The function works perfectly, but I would like to limit the amount of times a user can trigger the function to 10.

    How can I do this?

    Thanks in advance...

  2. #2
    Caveat surfer Buddy Bradley's Avatar
    Join Date
    May 2003
    Location
    Cambridge, UK
    Posts
    2,366
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Set a global counter, and check it/increment it each time?
    Code:
    var counter = 0;
    
    function copyTrue(){
      if (counter < 10) {
        var t = document.getElementById('roomdiv').cloneNode(true);
        document.getElementById('test1').appendChild(t);
        counter++;
        return true;
      }
    }

  3. #3
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I see another problem- 10 elements with the same id. But you can use
    the fix for this to limit the number of copies:

    function copyTrue(idstring){
    if(document.getElementById(idstring+'_9')) return;
    var t = document.getElementById(idstring).cloneNode(true);
    t.id=''; //remove the clone's id
    var n=1;
    var prefix=idstring+'_';

    while(document.getElementById(prefix+n))++n;// assign next unused id
    t.id= prefix+n;

    document.getElementById('test1').appendChild(t);
    return true;
    }

  4. #4
    SitePoint Wizard Zaggs's Avatar
    Join Date
    Feb 2005
    Posts
    1,048
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hey I managed to get it sorted!

    One further problem now is that I changed the <div> tags display property to none. How do I get the javascript to remove this property when the link is clicked?


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
  •