April 15, 2012

append to div one time

Question by Mr. 1.0

I am revisiting this code I made a year ago with the help of another person. Unfortunately I don’t have contact with them anymore to get more help. Basically It dynamically adds classs to the tb and b nodes of a document coming from namesToChange. Now what I am trying to do is append some text to the div with class dtxt node but still use this code below. I am using the code $('td.pn_adm_jeff').children('div.dtxt').append('zzz'); and it works but it constantly appends more than once as seen in the photo below. How do I go about making it add once and stop?

Photo
http://img6.imageshack.us/img6/5392/7c23ddb145954aefadb1b9f.png

Code

   function customizefields(a) {
        $('td b').each(function () {
            name = $(this).text();
            if (name.indexOf(" ") != -1) {
                name = name.substring(0, name.indexOf(" "))
            }
            if (a[name]) {
                this.className = a[name].class;
                this.parentNode.className = a[name].img
            }
        })
        $('td.pn_adm_jeff').children('div.dtxt').append('zzz');
    }

    var namesToChange = {
        'Jeff'    :{'class':'pn_adm','img':'pn_adm_jeff'}
    };

    setInterval(function () {
        customizefields(namesToChange)
    }, 1000);

Update

var needsUpdate = true;

function customizefields(a) {
    $('td b').each(function () {
        name = $(this).text();
        if (name.indexOf(" ") != -1) {
            name = name.substring(0, name.indexOf(" "));
        }
        if (a[name]) {
            this.className = a[name].class;
            this.parentNode.className = a[name].img;
        }
    });
    if (needsUpdate) {
        $('td.pn_adm_jeff').children('div.dtxt').append('testing');
        needsUpdate = false;
    }
}

var namesToChange = {
    'jeff'    :{'class':'pn_adm','img':'pn_adm_jeff'};
};

setTimeout(function () {
    customizefields(namesToChange);
}, 1000);

Answer by Ozzy

use setTimeout rather than setInterval (interval is for repeating a timer task, timeout is a single timer task)

To prevent a certain task from occuring more than once in a repeated task, there is a simple fix.

// global variable
var needsUpdate = true;

// now in the timer task
if (needsUpdate) {
    $('td.pn_adm_jeff').children('div.dtxt').append('zzz');
    needsUpdate = false;
}

Does that work for you?

Answer by Starx

Define a global variable to hold the input flag

var appended = false;

function appendthestring() {
   if(!appended) $('td.pn_adm_jeff').children('div.dtxt').append('zzz');
   appended = true; 
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!