Search code examples
jqueryclickpersistdynamic-html

Track Values to Prevent Dynamic HTML Being Re-created Via Click


I have a simple jQuery .click() function:

$(".clicky a").click(function(e){
   e.preventDefault();
   var val = $(this).html();
   stuffCreate(val);
});

being used to drive the dynamic generation of HTML code:

function stuffCreate(stuff) {
   var firststuff ="<div class='cont'><strong>"+stuff+"</strong></div>";
   $(firststuff).appendTo("#data"+stuff+" .innertables");
}

The var val is always an integer and there are a bunch of them on the page. What I want to do is have some means of tracking the clicks I've made and preventing the dynamic HTML from be re-created with every subsequent click -- I want to keep that generated HTML, er, generated, i.e. unchanged, persistent and accessible as it was generated on that initial click. I tried using an array to track clicks but couldn't figure out how to leverage those values to prevent re-creating the dynamic HTML with every click after the first. I welcome whatever help you can provide here.


Solution

  • If you want to run a function the first time the element is clicked but still keep track of subsequent clicks then you can have a simple counter property attached to the listener:

    $('a').on('click', function(e) {
        this.counter = this.counter || 0;
        this.counter++;
        if (this.counter <= 1) {
            // do something
        }
    });
    

    Example

    http://jsfiddle.net/q3LVS/1/