Hide DIVs after function has completed his task - javascript

I wrote a piece of code that auto replies to user text input.
An automated "live chat" so to say.
Though when the script runs out of responses I want it to disable the subit form and button, I don't really have any clue on how to do such a thing.
My code:
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(document).ready(function() {
$("#typing").hide();
var n = "You:<br>";
var o = $('#outputWindow');
var i = $('#inputWindow');
var s = $('#sendButton');
var t = $('#typing');
var r = -1;
//arrays
var msg = ['msg1', 'msg2', 'msg3'];
//fire send events
$(s).click(function() {
runAI();
});
$(i).keydown(function(e) {
if (e.keyCode == 13) {
runAI();
}
});
function runAI() {
if (i.val().length > 0) {
r = r + 1;
o.html(o.html()+n+$("#inputWindow").val()+"<br><hr>" );
setTimeout(function(){ $("#typing").show(); }, 3000);
setTimeout(function(){ o.html(o.html()+"Username:<br>"+msg[r]+"<br><hr>") }, 7000);
setTimeout(function(){ $("#typing").hide(); }, 8000);
i.val('');
i.focus();
}
}
i.focus();
});
});//]]>
</script>
The idea is to hide the submit form and button after (in the case) the script has responded with: msg1, msg2 and msg3.
If anyone can help, that'd be great !

This will do that. Place at the bottom of the runAI() function.
this will check r+1 each time runAi() is invoked. When it detects that it's greater than or equal to the message array length it will hide the user input possibilities after the last message is sent.
function runAI() {
if (i.val().length > 0) {
r = r + 1;
o.html(o.html()+n+$("#inputWindow").val()+"<br><hr>" );
setTimeout(function(){ $("#typing").show(); }, 3000);
setTimeout(function(){ o.html(o.html()+"Username:<br>"+msg[r]+"<br><hr>") }, 7000);
setTimeout(function(){ $("#typing").hide(); }, 8000);
if (r+1 >= msg.length)
{
$('#inputWindow').hide();
$('#sendButton').hide();
return true; // end the function here;
}
else
{
i.val('');
i.focus();
}
}
}
When r reaches a length greater than or equal to the length of the array the input and button is hidden.

Well, simply use CSS to hide it:
$(<your object>).css('display', 'none');
use this for every object you want to hide. Go to www.w3schools.com and check out the posible values for the display property.

Related

cannot set innerHTML property of null on Qualtrics

I am using Qualtrics to make a survey, and I need to do a bit of JS to make a timer. Unfortunately, I'm constantly running into "cannot set innerHTML property of null" for element "s5".
I've read the other thread about this issue (albeit the OP doesn't seem to be using qualtrics), and thought that perhaps changing "Qualtrics.SurveyEngine.addOnload" to "Qualtrics.SurveyEngine.addReady" might do the trick, but it doesn't, and I've already tried changing the id's quite a few times to no avail. Could someone help me find where my error is?
I got marked previously for the same question (as something that's already been answered), but that thread didn't help me at all. I've tried ready() as shown in the commented out section in the first code snippet, but that only gave me a "startThinkingTimer is not defined" error. When I tried it the second way in the second code snippet, I didn't get any errors, but my timer wasn't visible/working at all either. I can't move script or use defer b/c Qualtrics does not have all the HTML/CSS/JS in one file, but has different sections for them and honestly I'm not sure how they connect the different files. Regarding using .on(), I'm not sure which event to use here, and would really like some help.
I've tried replacing all the document.getElementById for element "s5" with something like this:
$("s5").innerHTML="10";
but this doesn't work, either.
(Should I try to move the html code inside the JS portion (esp. the div timeShower part)? I'm not too sure how to do that though, so if someone could help me do that, that'd be awesome.)
window.thinkingTimer_;
window.typingTimer_;
Qualtrics.SurveyEngine.addOnload(function(){
that = this;
var thinkingTimeLimit = 15;
var typingTimeLimit = 10;
jQuery(".InputText").hide();
$('NextButton').hide();
document.getElementById("instructions5").innerHTML = "You have 15 seconds to think about the prompt and come up with your two most favourite fruits, either from the list or from your previous choices. Textboxes will appear when the time is up.";
function startTypingTimer() {
that.enableNextButton();
typingTimer_ = setInterval( function(){
if (typingTimeLimit > 0) {
document.getElementById("s5").innerHTML=pad(--typingTimeLimit%60);
document.getElementById("minutes5").innerHTML=pad(parseInt(typingTimeLimit/60,10));
}
if (typingTimeLimit == 0) {
clearInterval(typingTimer_);
jQuery("#NextButton").click();
}
}, 1000);
}
/*
$(function startThinkingTimer() {
that.disableNextButton();
thinkingTimer_ = setInterval( function(){
if (thinkingTimeLimit >0) {
document.getElementById("s5").innerHTML=pad(--thinkingTimeLimit%60);
document.getElementById("minutes5").innerHTML=pad(parseInt(thinkingTimeLimit/60,10));
}
if (thinkingTimeLimit == 0) {
clearInterval(thinkingTimer_);
document.getElementById("s5").innerHTML="10";
document.getElementById("minutes5").innerHTML="00";
jQuery(".InputText").show();
document.getElementById("instructions5").innerHTML = "You now have 10 seconds to type in the two fruits. The page will automatically move on to the next page once time is up.";
startTypingTimer();
}
}, 1000);
});
*/
function startThinkingTimer() {
that.disableNextButton();
thinkingTimer_ = setInterval( function(){
if (thinkingTimeLimit >0) {
document.getElementById("s5").innerHTML=pad(--thinkingTimeLimit%60);
document.getElementById("minutes5").innerHTML=pad(parseInt(thinkingTimeLimit/60,10));
}
if (thinkingTimeLimit == 0) {
clearInterval(thinkingTimer_);
document.getElementById("s5").innerHTML="10";
document.getElementById("minutes5").innerHTML="00";
jQuery(".InputText").show();
document.getElementById("instructions5").innerHTML = "You now have 10 seconds to type in the two fruits. The page will automatically move on to the next page once time is up.";
startTypingTimer();
}
}, 1000);
}
function pad (val) {
return val > 9 ? val : "0" + val;
}
startThinkingTimer();
});
<div id="instructions5"> </div>
<div id="timeShower1">time: <span id="minutes5">00</span>:<span id="s5">15</span></div>
window.thinkingTimer_;
window.typingTimer_;
Qualtrics.SurveyEngine.addOnload(function(){
that = this;
var thinkingTimeLimit = 15;
var typingTimeLimit = 10;
jQuery(".InputText").hide();
$('NextButton').hide();
document.getElementById("instructions5").innerHTML = "You have 15 seconds to think about the prompt and come up with your two most favourite fruits, either from the list or from your previous choices. Textboxes will appear when the time is up.";
function startTypingTimer() {
that.enableNextButton();
typingTimer_ = setInterval( function(){
if (typingTimeLimit > 0) {
document.getElementById("s5").innerHTML=pad(--typingTimeLimit%60);
document.getElementById("minutes5").innerHTML=pad(parseInt(typingTimeLimit/60,10));
}
if (typingTimeLimit == 0) {
clearInterval(typingTimer_);
jQuery("#NextButton").click();
}
}, 1000);
}
$(function () {
that.disableNextButton();
thinkingTimer_ = setInterval( function(){
if (thinkingTimeLimit >0) {
document.getElementById("s5").innerHTML=pad(--thinkingTimeLimit%60);
document.getElementById("minutes5").innerHTML=pad(parseInt(thinkingTimeLimit/60,10));
}
if (thinkingTimeLimit == 0) {
clearInterval(thinkingTimer_);
document.getElementById("s5").innerHTML="10";
document.getElementById("minutes5").innerHTML="00";
jQuery(".InputText").show();
document.getElementById("instructions5").innerHTML = "You now have 10 seconds to type in the two fruits. The page will automatically move on to the next page once time is up.";
startTypingTimer();
}
}, 1000);
});
/*
function startThinkingTimer() {
that.disableNextButton();
thinkingTimer_ = setInterval( function(){
if (thinkingTimeLimit >0) {
document.getElementById("s5").innerHTML=pad(--thinkingTimeLimit%60);
document.getElementById("minutes5").innerHTML=pad(parseInt(thinkingTimeLimit/60,10));
}
if (thinkingTimeLimit == 0) {
clearInterval(thinkingTimer_);
document.getElementById("s5").innerHTML="10";
document.getElementById("minutes5").innerHTML="00";
jQuery(".InputText").show();
document.getElementById("instructions5").innerHTML = "You now have 10 seconds to type in the two fruits. The page will automatically move on to the next page once time is up.";
startTypingTimer();
}
}, 1000);
}*/
function pad (val) {
return val > 9 ? val : "0" + val;
}
//startThinkingTimer();
});

Javascript clearInterval does not stop setInterval

I have a javascript code that shows some messages every 6 seconds using setInterval function as bellow:
$(function () {
count = 0;
wordsArray = ["<h1>Offer received</h1>", "<h1>Offer reviewed</h1>", "<h1>Decision pending</h1>", "Offer accepted.</h1>"];
setInterval(function () {
$(".lead").fadeOut(400, function () {
$(this).html(wordsArray[count % wordsArray.length]).fadeIn(400);
});
if(count === 3){
clearInterval(window.location.href = "www.mydomain.com");
}
count++;
}, 6000);
});
When the last message is displayed I want to redirect to a URL so I checked the counter and placed a clearInterval when the last message is displayed however it does not go to the url right after the last massage is displayed but geos back to the first one and then redirect, sounds like it continues to loop. How can I fix that please?
Thanks
An interval id is returned by setInterval , you need to use that to stop particular interval.
$(function() {
count = 0;
wordsArray = ["<h1>Offer received</h1>", "<h1>Offer reviewed</h1>", "<h1>Decision pending</h1>", "<h1>Offer accepted.</h1>"];
var intervalTimer = setInterval(function() {
$(".lead").fadeOut(400, function() {
$(this).html(wordsArray[count % wordsArray.length]).fadeIn(400);
});
if (count === 3) {
clearInterval(intervalTimer);
}
count++;
}, 6000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="lead"></div>

Disable the function of a submit button in a html form with jquery, but still have it visible

As you can see in the code below, I am making an automated chat.
The user inputs text and the code responds with a message.
It's working alright so far but right now I want to prevent the user sending another message before my message appears.
So lets say the user sends a message, after that the submit button becomes disabled, preventing the user from sending more messages. When the code responds, the button comes availible again.
I don't want to hide the button, but I want to disable it's function.
That way it'd still be visible, just not functional while the function runAI is running.
If someone can help, that'd be great.
Code:
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(document).ready(function() {
$("#typing").hide();
var n = "You:<br>";
var o = $('#outputWindow');
var i = $('#inputWindow');
var s = $('#sendButton');
var t = $('#typing');
var r = -1;
//arrays
var msg = ['msg1', 'msg2', 'msg3'];
//fire send events
$(s).click(function() {
runAI();
});
$(i).keydown(function(e) {
if (e.keyCode == 13) {
runAI();
}
});
function runAI() {
if (i.val().length > 0) {
r = r + 1;
o.html(o.html()+n+$("#inputWindow").val()+"<br><hr>" );
setTimeout(function(){ $("#typing").show(); }, 3000);
setTimeout(function(){ o.html(o.html()+"Username:<br>"+msg[r]+"<br><hr>") }, 7000);
setTimeout(function(){ $("#typing").hide(); }, 8000);
if (r+1 >= msg.length)
{
setTimeout(function(){$('#inputWindow').hide(); }, 8000);
setTimeout(function(){$('#sendButton').hide(); }, 8000);
return true; // end the function here;
}
else
{
i.val('');
i.focus();
}
}
}
});
});//]]>
</script>
As per the latest jQuery Docs which was last updated January 26, 2015.
// Disable
$( "#sendButton" ).prop( "disabled", true );
// Enable
$( "#sendButton" ).prop( "disabled", false );
To disable the button :
$("#buttonId").prop("disabled",true);
And to enable the button :
$("#buttonId").prop("disabled",false);
I would integrate in your code like this ;
$(s).click(function() {
$("#buttonId").prop("disabled",true);
runAI();
});
$(i).keydown(function(e) {
if (e.keyCode == 13) {
$("#buttonId").prop("disabled",true);
runAI();
}
});
And then when runAI() is done :
function runAI() {
if (i.val().length > 0) {
r = r + 1;
o.html(o.html()+n+$("#inputWindow").val()+"<br><hr>" );
setTimeout(function(){ $("#typing").show(); }, 3000);
setTimeout(function(){ o.html(o.html()+"Username:<br>"+msg[r]+"<br><hr>") }, 7000);
setTimeout(function(){ $("#typing").hide(); }, 8000);
if (r+1 >= msg.length)
{
setTimeout(function(){$('#inputWindow').hide(); }, 8000);
setTimeout(function(){$('#sendButton').hide(); }, 8000);
return true; // end the function here;
}
else
{
i.val('');
i.focus();
}
$("#buttonId").prop("disabled",false);
}
}
document.getElementById("Submit").disabled = true;
Use:
$("#buttonId").prop("disabled",true);
To disable the button
$('input[type="submit"], input[type="button"], button').disable(true);
To enable the button again
$('input[type="submit"], input[type="button"], button').disable(false);
Of course the selector should be matching your submit button. my example would disable all buttons on your page

Javascript : Do Action after elapsed time

I have a page where I fire an ajax request AND show a loading sign for the first 6 seconds after the user presses a button :
<button onclick="runLoader();"></button>
<script>
var startTime=(new Date).getTime();
function runLoader(){
runAjax();
var i=0;
var timer = setInterval(function(e){
i++;
//code for loading sign
if(i==3)
clearInterval(timer);
} ,2000);
}
function runAjax(){
$.ajax({
//
}).done(function(){
var timer2 = setInterval(function(){
var d = new Date();
var t = d.getTime();
if(t-startTime>=6000){
clearInterval(timer2);
// do X
}
},500);
}
}
</script>
I want to do action X only after both runLoader() has run for 6 seconds and runAjax() has resulted in a response, and no sooner.
Like, if runAjax() responds in 2 seconds, I still want to continue showing loading sign for 6 seconds and then perform X.
And if the loading sign has shown for 6 seconds, I want to wait for runAjax() to return for as long as it takes.
But using the Date() method is giving inaccurate results. For eg : It shows 7.765 s elapsed even when only 2 s have passed. I read somewhere I should use console.log(time) for better accuracy, but it doesnt work in <=IE9.
Is there a better way to approach this problem ?
Note: I am using setInterval() instead of setTimeout() because the loading involves cycling through an array of 3 elements, "Fetching", "Processing" and "Loading" each shown for 2 seconds :)
I would use deferreds and $.when:
function start(){
$.when(runLoader(), runAjax()).done(function() {
//both are now finished
});
}
function runLoader() {
//show loader here
var def = $.Deferred();
setTimeout(function() {
//hide loader here
def.resolve(true);
}, 6000);
return def.promise();
}
function runAjax() {
var def = $.Deferred();
$.ajax({...}).done(function(result) {
//handle response here
def.resolve(true);
});
return def.promise();
}
I would set a flag to mark it as "ready". There may be better ways to handle this, but this is just off the top of my head.
<script>
function runLoader(){
runAjax();
var i=0;
var timer = setInterval(function(e){
i++;
//code for loading sign
if(i==3)
clearInterval(timer);
} ,2000);
}
function runAjax(){
var timeElapsed = false;
setTimeout(function(){timeElapsed = true}, 6000);
$.ajax({
//
}).done(function(){
var timer2 = setInterval(function(){
if(timeElapsed){
clearInterval(timer2);
// do X
}
},500);
}
}
</script>
You can create a pre-caller function that is run on runLoader() and as callback of runAjax(), that will verify if the other action is complete, and then do action X. Example:
var ajaxDone = false;
var loaderDone = false;
function doActionX() {
//your action happens here
}
function tryToDoX() {
if (ajaxDone && loaderDone) {
doActionX();
}
}
function runLoader(){
loaderDone = false;
runAjax();
//show loading sign
setInterval(function(e){
//hide loading sign
clearInterval(timer);
loaderDone = true;
tryToDoX();
}, 6000);
}
function runAjax(){
ajaxDone = false;
$.ajax({
//whatever
}).done(function(){
ajaxDone = true;
tryToDoX();
}
}
It isn't necessary to make a recurring timeout and poll both statuses, because they only get completed once (in every run, i.e. booleans aren't set to false and true while waiting).
EDIT: This approach can be used to any asynchronous code that doesn't change status intermitently, even without jQuery.

Repeat code every x seconds but not if [insert check here]

This is a followup to this question, where I found out how to make code be repeated every x seconds. Is it possible to make an event that can change this? I.e. I have a checkbox which is meant to control whether this is repeated or not, so I figured I'd need something like this:
$(checkbox).bind("change", function() {
switch(whether if it is ticked or not) {
case [ticked]:
// Make the code repeat, while preserving the ability to stop it repeating
case [unticked]:
// Make the code stop repeating, while preserving the ability to start again
}
});
I have no idea what I could put in the cases.
You can do it by assigning your setInterval function to a variable.
var interval = setInterval(function() { }, 1000);
and then you can stop setInterval by
clearInterval(interval);
p.s.
to start your interval you need to call var interval = setInterval(function() { }, 1000); again
You can either stop and start the interval:
var timer;
function start() {
timer = window.setInterval(function(){
// do something
}, 1000);
}
function stop() {
window.clearInterval(timer);
}
start();
$(checkbox).bind("change", function() {
if ($(this).is(':checked')) {
start();
} else {
stop();
}
});
Or you can have a flag causing the interval to skip the code:
var enabled = true;
var timer = window.setInterval(function(){
if (!enabled) {
// do something
}
}, 1000);
$(checkbox).bind("change", function() {
enabled = $(this).is(':checked');
});
function fooFunc() {
$('#foo').text(+new Date());
}
var id;
var shouldBeStopped = false;
$('input').change(function() {
if (shouldBeStopped)
clearInterval(id);
else
id = setInterval(fooFunc, 200);
shouldBeStopped = !shouldBeStopped;
});​
Live DEMO

Categories