append to div one time - javascript

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);

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?

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;
}

Related

How To Stop all Functions in JavaScript using an IF Function

I'm trying to use one function and a lot of IF functions to run this code.
I'm going to make this as a note app.
I want to add an IF function that has an class called stop-note.
I want to add it in the notes list for it's IF function then I want to add it to the "renderNotes" for it's link like style.
notesList.on('click', function (e) {
e.preventDefault();
var target = $(e.target);
var abort = false;
// Listen to the selected note.
if (target.hasClass('listen-note')) {
if (abort) {
return;
}
var content = target.closest('.note').find('.content').text();
readOutLoud(content);
}
//Edit Note
if (target.hasClass('edit-note')) {
editText(content);
var dateTime = target.siblings('.date').text();
deleteNote(dateTime);
target.closest('.note').remove();
var content = target.closest('.note').find('.content').text();
}
// Delete note.
if (target.hasClass('delete-note')) {
var dateTime = target.siblings('.date').text();
deleteNote(dateTime);
target.closest('.note').remove();
}
});
This is my function that runs my function above.
function renderNotes(notes) {
var html = '';
if (notes.length) {
notes.forEach(function (note) {
html += `<li class="note">
<p class="header">
<span class="date">${note.date}</span>
Listen
Edit
html = <button class="stop-note" onclick="abort = true">Stop</button>
Delete
</p>
<p class="content">${note.content}</p>
</li>`;
});
} else {
html = '<li><p class="content">You don\'t have any notes yet.</p></li>';
}
notesList.html(html);
}
abort is a local variable, and you set it to false whenever they click on a note list. So onclick="abort = true" has no effect on the variable that's being tested in the function.
You need to make it a global variable.
window.abort = false;
notesList.on('click', function (e) {
e.preventDefault();
var target = $(e.target);
// Listen to the selected note.
if (target.hasClass('listen-note')) {
if (abort) {
return;
}
var content = target.closest('.note').find('.content').text();
readOutLoud(content);
}
//Edit Note
if (target.hasClass('edit-note')) {
editText(content);
var dateTime = target.siblings('.date').text();
deleteNote(dateTime);
target.closest('.note').remove();
var content = target.closest('.note').find('.content').text();
}
// Delete note.
if (target.hasClass('delete-note')) {
var dateTime = target.siblings('.date').text();
deleteNote(dateTime);
target.closest('.note').remove();
}
});

jQuery Trigger Click not work at first click

I have a trouble with jquery trigger click. I need to play audio from audio tag via trigger click. When i click first time on first element it work, but if I click in another element, the first click not work. If i click 2nd time it will be work.
var Audioplaying = false;
jQuery('.playAudio').click(function(e) {
var playerID = jQuery(this).next('.audioPlayer').attr('id');
var playerBTN = jQuery(this);
if (Audioplaying == false) {
Audioplaying = true;
jQuery("#"+playerID)[0].play();
playerBTN.addClass('play');
} else {
Audioplaying = false;
jQuery("#"+playerID)[0].pause();
playerBTN.removeClass('play');
}
e.preventDefault();
});
The variable Audioplaying is shared, it is not unique so you probably want it to be unique per element. So use data() to keep track of the state for each player.
jQuery('.playAudio').click(function(e) {
var player = jQuery(this).next('.audioPlayer');
var playerID = player.attr('id');
var playerState = player.data('isPlaying') || false; // get if it is running
player.data('isPlaying', !playerState); // update the boolean
var playerBTN = jQuery(this);
if (!playerState) {
jQuery("#"+playerID)[0].play();
playerBTN.addClass('play');
} else {
jQuery("#"+playerID)[0].pause();
playerBTN.removeClass('play');
}
e.preventDefault();
});
Maintain the state of each button separately. so, you can use an object with it's 'id' as the key.
example : { button_id : true/false }
var Audioplaying = {};
jQuery('.playAudio').click(function(e) {
var playerID = jQuery(this).next('.audioPlayer').attr('id');
var playerBTN = jQuery(this);
if (!Audioplaying[playerID]) {
Audioplaying[playerID] = true; // every button has it's own state maintained in the object.
jQuery("#"+playerID)[0].play();
playerBTN.addClass('play');
} else {
Audioplaying[playerID] = false;
jQuery("#"+playerID)[0].pause();
playerBTN.removeClass('play');
}
e.preventDefault();
});
Hope it helps you arrive at a optimal solution.

jQuery change event code not running possible event conflict

Let me start off by saying that this is my second day learning jQuery so I'm very much a beginner.
I've written a document ready function and all components are working except the countryField.change function I wrote. I'm pretty sure the web application already has a change function for this field and I'm not sure if there can be two of the same event on a field. When I say it's not working, I set a breakpoint in the Chrome debugger and it never enters the function.
Maybe I have to temporarily pause the existing event, run my code, then re-enable the default event?
Any help would be appreciated. Thanks.
$(document).ready(function(){
var submitReady = true;
var phoneField = $("p.phone").find("input");
var phoneExt = $("p.Ext").find("input");
var countryField = $("p.country").find("input");
var stateField = $("p.state").find("input");
var provinceField = $("p.Province").find("input");
var regex = /^\([2-9][0-9]{2}\)\s+[2-9][0-9]{2}\-[0-9]{4}$/;
phoneField.mask('(000) 000-0000', {placeholder: "(###) ###-####"});
phoneExt.mask('00000', {placeholder: "#####"});
$('#pardot-form').submit(function() {
// DO STUFF
if (submitReady) {
if (phoneExt.val() != "") {
phoneField.val(phoneField.val() + ' x' + phoneExt.val());
return true;
}
}
else {
return false;
}
});
phoneField.focusout(function() {
if (regex.test($(this).val())) {
submitReady = true;
return true;
}
else {
$(".form-field.phone").after( "<p class='tempError error no-label'>Please Enter a valid phone number: (###) ###-####</p>");
submitReady = false;
}
});
phoneField.focus(function() {
$(".tempError").remove();
});
countryField.change(function() {
phoneField.val("");
provinceField.val("");
stateField.val("");
submitReady = true;
});
});
You can try
$( "p.country" ).change(function() {
phoneField.val("");
provinceField.val("");
stateField.val("");
submitReady = true;
});

How to detect if some text box is changed via external script?

I have some jQuery plugin that changes some elements, i need some event or jQuery plugin that trigger an event when some text input value changed.
I've downloaded jquery.textchange plugin, it is a good plugin but doesn't detect changes via external source.
#MSS -- Alright, this is a kludge but it works:
When I call boxWatcher() I set the value to 3,000 but you'd need to do it much more often, like maybe 100 or 300.
http://jsfiddle.net/N9zBA/8/
var theOldContent = $('#theID').val().trim();
var theNewContent = "";
function boxWatcher(milSecondsBetweenChecks) {
var theLoop = setInterval(function() {
theNewContent = $('#theID').val().trim();
if (theOldContent == theNewContent) {
return; //no change
}
clearInterval(theLoop);//stop looping
handleContentChange();
}, milSecondsBetweenChecks);
};
function handleContentChange() {
alert('content has changed');
//restart boxWatcher
theOldContent = theNewContent;//reset theOldContent
boxWatcher(3000);//3000 is about 3 seconds
}
function buttonClick() {
$('#theID').value = 'asd;lfikjasd;fkj';
}
$(document).ready(function() {
boxWatcher(3000);
})
try to set the old value into a global variable then fire onkeypress event on your text input and compare between old and new values of it. some thing like that
var oldvlaue = $('#myInput').val();
$('#myInput').keyup(function(){
if(oldvlaue!=$('#myInput').val().trim())
{
alert('text has been changed');
}
});
you test this example here
Edit
try to add an EventListner to your text input, I don't know more about it but you can check this Post it may help
Thanks to #Darin because of his/her solution I've marked as the answer, but i have made some small jQuery plugin to achieve the same work named 'txtChgMon'.
(function ($) {
$.fn.txtChgMon = function (func) {
var res = this.each(function () {
txts[0] = { t: this, f: func, oldT: $(this).val(), newT: '' };
});
if (!watchStarted) {
boxWatcher(200);
}
return res;
};
})(jQuery);
var txts = [];
var watchStarted = false;
function boxWatcher(milSecondsBetweenChecks) {
watchStarted = true;
var theLoop = setInterval(function () {
for (var i = 0; i < txts.length; i++) {
txts[i].newT = $(txts[i].t).val();
if (txts[i].newT == txts[i].oldT) {
return; //no change
}
clearInterval(theLoop); //stop looping
txts[i].f(txts[i], txts[i].oldT, txts[i].newT);
txts[i].oldT = $(txts[i].t).val();
boxWatcher(milSecondsBetweenChecks);
return;
}
}, milSecondsBetweenChecks);
}

How do I move image in the front of Download Now in javascript code?

How do I move this image http://svastara.info/.s/img/icon/download1.png in the front of Download now?
Should look something like this: image Download Now
var CountdownTimer = function( id, count, imgurl ) { this.construct(id, count, imgurl); }
CountdownTimer.prototype = {
construct: function(id,count,imgurl) {
this.id = id;
this.object = document.getElementById(id);
this.count = count;
this.interval = null;
this.counted = false;
this.img = new Image(); // preload
this.img.src = imgurl;
this.img.border = "0";
(function(obj) {
obj.object.onclick = function() {
return obj.onclick();
};
})(this);
},
tick: function() {
this.count--;
this.render();
if(this.count == 0){
clearInterval(this.interval);
this.interval = null;
this.object.appendChild(this.img);
}
},
onclick: function() {
if(!this.counted) {
this.counted = true;
this.render();
(function(obj) {
obj.interval = setInterval(function() {
obj.tick();
},1000);
})(this);
return false;
} else if(this.count == 0)
return true;
else
return false;
},
render: function() {
if(this.count > 0)
this.object.innerHTML = "Download (" + this.count + " second" + (this.count == 1 ? "" : "s") + ")";
else
this.object.innerHTML = "Download Now";
}
};
window.onload = function() {
var c = new CountdownTimer("delayed",3,"http://svastara.info/.s/img/icon/download1.png");
};
<div>
<a id="delayed" class="stop" href="http://www.epiclosers.com/">Download (30sec)</a>
</div>
Have a look at the insertBefore method, the existing text should be a child node of the anchor tag.
Having said that, I'm beginning to wonder why people are doing the fancy thing here... You're not unique, I see this sort of thing all the time. The code can be simplified by allowing HTML and CSS to help you. Put the image in the document, set the display to none, and turn it on when you need it. Also, the text after download can be in a span that is also updated as you require. Then whole thing can be managed with a fraction of the code. Final thought on the simplification, you can just disable the link until you're ready to allow.
Also, using a simple debugger in the client, I can change the count to 0 on the fly and bypass the logic altogether. Or, even easier, I can just turn off javascript and click the link. In other words, make sure you're enforcing it through other means that aren't in the client. It's always a bad idea to rely on the client to enforce policy, so back it up on the server side. You may be doing that, so please don't be offended by the comment.

Categories