jQuery taking live input and then simulating typing - javascript

I'm having some issues with simulating live typing with jQuery. My Javascript is as follows (with a live demo here).
$(document).ready(function () {
var keystrokes = [];
var value = "";
var counter = 0;
window.setInterval(pushKeystrokes, 100);
function pushKeystrokes() {
keystrokes.push({
value: value
});
}
$("#test").keyup(function () {
value = $(this).val();
});
$("#button").click(function () {
$("#test").val("");
$.each(keystrokes, function () {
window.setTimeout(function () {
$("#test").val(keystrokes[counter].value);
}, 100 * counter);
counter++;
});
});
});
This is supposed to wait for input to a text field called test, and as soon as a button is clicked, it should clear that text field and simulate typing the characters the user typed in real-time. For some reason, my call to setTimeout only produces the very last value in the array.
However, if I set Math.random as the value of the text field in the setTimeout instead of keystrokes[counter].value, it seems to update fine every 100 milliseconds as it should. What exactly am I doing wrong? I'm guessing it has something to do with scope.
Edit:
Sorry I wasn't clear. I would like to preserve delays in user action, i.e. waiting a few seconds before typing, typing words at different speeds, etc. Is this still possible?

I've edited the code you posted in your JSBin, modified a few things here and there.
The logic behind the rewritten script is added in the form of comments.
Here's an example

Try this example http://jsbin.com/eVOcOku/4/.
In your example you have additional issue with timeInterval.

There are a few problems you're having here, some to do with unnecessary code, and some to do with the nature of setTimeout
First of all the pushKeyStrokes() function seems dodgy; it only checks every 100 ms? Besides, it's not needed because later you can just go through the string provided by the input once the button is pressed, and you can do that using charAt.
Secondly, you're referring to the value "counter" within your setTimeout function, but by the time that function is called the counter value will have reached the length of the input string; counter++ will already have been called every time before the first call to the character display function is even made!
In any case, I modified your JS Bin; hope it makes sense and let me know if you have any questions:
$(document).ready(function() {
var value = "";
$test = $("#test");
$("#button").click(function() {
value = $test.val();
$test.val("");
for (var i = 0; i < value.length; i++)
{
window.setTimeout(addChar, 100 * i, value.charAt(i));
}
function addChar(char)
{
$test.val($test.val() + char);
}
});
});

Related

How to have a variable increase over time (JS)

i was wondering how to make a variable go up over time, ive tried to do this -->
var i = 1;
var c = document.getElementById("click");
function workers() {
if (click >= workers*50000)) {
click += -(workers*50000)
click += i++
c.innerHTML = click;
}
}
but it hasnt worked, how do i fix this?
you could do this
let i = 0;
// instead of 2000 insert the frequency of the wanted update (in milliseconds)
const incrementInterval = setInterval(() => i++, 2000)
// when you want it to stop it
clearInterval(incrementInterval)
anyway, i don't really understand how the code supplied with the question has anything to do with it
You have an element and a variable 'click', which tells me you're really not wanting to grow over time per se, but rather grow with every click.
Another difficulty is finding out what you're trying to do with multiplying by 50000. I am assuming you are trying to reset the count after 50000.
One big thing you're missing is the actual association of the click event to your 'click' HTML element. Below, I'm using addEventListener to do that. From there, I'm resetting the counter to '1' if 'i' goes above '5' (I use 5 just to show the reset in a reasonable number of clicks). Then I take the value of 'i' and put it into the innerHTML label of the element that triggered the event.
var i = 1;
document
.getElementById("click")
.addEventListener('click', function(e) {
if (i > 5)
i = 1;
e.target.innerHTML = `click: ${i++}`;
})
<div id='click'>click<div>
Define your question better. What is your goal? What has your code achieved? What result are you getting and how is it different than your expectations? What is 'i' meant to be used for? How does it interact with the function? Why are you multiplying it with 50000? Is workers a separate variable that's globally defined and not shown? Communication is an important skill in this field, and comments are often helpful tools to document your code for others to understand.
I think an alternative answer could be formatted in this way:
let i = 0;
function increment(){
i++;
document.querySelector('h3').textContent = i
}
document.querySelector('button').addEventListener('click',increment)
<button>Click Me</button>
<h3>0</h3>

How to write a generic function that passes one argument to then function then called multiple times

I have been stuck on this homework:
Create a generic function that outputs one line of the countdown on
the web page, followed by an alert, and receives the data to output as
an input parameter.
Use that function to output each line of the countdown, and an alert.
Please note that you are outputting the countdown to the browser
window this time, not to an alert!
The alert is only being used to signal when to output the next line
I need help in how to come up with a generic function that passes only one argument and then can be called 13 times. To write a for loop that output the numeric part of a countdown.
I think the key here is that they're asking for "Generic".
That means one function that doesn't have to know anything but what it's doing.
It also usually means that it shouldn't remember anything about what it did last time, or what it's going to do next time it's called (unless you're writing a generic structure specifically for remembering).
Now, the wording of the specification is poor, but a generic function which:
takes (input) data to write
writes the input to the page
calls an alert
is much simpler than you might think.
var writeInputAndAlert = function (input) {
// never, ever, ***ever*** use .write / .writeLn in the real world
document.writeLn(input);
window.alert("next");
};
If I was your teacher, I would then rewrite window.alert to handle the non-generic portion.
It's non-generic, because it knows the rules of the program, and it remembers where you are, and where you're going.
var countFrom = 100,
currentCount = countFrom,
countTo = 0;
var nextCount = function () {
currentCount -= 1;
if (currentCount >= countTo) { writeInputAndAlert(currentCount); }
};
window.alert = nextCount;
edit
var countdownArray = ["ten", "nine", "eight", "Ignition Start", "Lift Off", "We have Lift Off"],
i = 0, end = countdownArray.length, text = "",
printAndAlert = function (item) {
alert();
document.write(item);
};
for (; i < end; i += 1) {
text = countdownArray[i];
printAndAlert(text);
}
This really doesn't need to be any harder than that.
printAndAlert is a generic function that takes one input, writes that input and triggers an alert.
You call it inside of a for loop, with each value in your array.
That's all there is to it.
If I understand correctly, you want to create a function that will allow you to pass the data once, and then you can call that function to output the data line by line.
To do this exactly that way isn't possible, but this method is almost the same:
function createOutputFunction(dataArray)
{
return function() {
document.write(dataArray.shift()); // This writes the first element of the dataArray to the browser
};
}
//It can then be used like this
outputFunction = createOutputFunction(["Banana", "Mango", "Apple"]);
outputFunction();
outputFunction();
outputFunction();
The "createOutputFunction" function returns a function that can read the "dataArray" variable and print its first element every time it is called.

Making a total number count appear to increase

Basically I have a class counting system that displays the number of classes and displays them in a span element. Below is the code:
$.get('other.html', function(data) {
$('#total').html($('.doc', data).length);
});
This works perfectly, however I'd like a way to have the numbers increasing one by one since the span element contains 0 when the page loads. Here's an example (the numbers increasing on here).
For this I have tried setTimeout and despite this not working anyway, I released it would simply delay the function and then display the end number. I have heard of periodical or something similar being used but could not find this in the example source code.
I am really sorry for more poor phrasing. If you have no idea what I mean then just ask and I'll try rephrase or find a better example.
The key is the function which increases the number should set a setTimeout to call itself, before termination. This way it will always be called again. If you want the option to stop the incrementing, you can add a global variable, and the function will only set a new timeout when that variable is true.
Example:
var doIncrement = true;
var numberToIncrement = 0;
function increment {
numberToIncrement++;
$('#mySpan').text(numberToIncrement);
if (doIncrement) {
setTimeout(increment, 1000);
}
}
You could use the setInterval function that allows you to run code at some time intervals. clearInterval allows to stop the task.
http://jsfiddle.net/d52Pw/
var $totalEl = $('#total');
$.get('other.html', function(data) {
var len = $('.doc', data).length,
count = 0,
int = setInterval(function () {
if (++count === len) {
//when we reach len, we stop the task
clearInterval(int);
}
$totalEl.html(count);
}, 500); //run every 1/2 sec
});

How to assign the value of 0 to a variable?

Javascript function 1:
var count = 0;
function myFunction()
{
count++;
document.getElementById("count").innerHTML=count;
}
Javascript function 2:
function demo() {
var y=document.getElementById("count").innerHTML;
if(y=="0") {
alert("There's nothing to be reset.");
}
else {
var count=0;
alert("Reset.");
// alternative code I used: document.getElementById("count").innerHTML="0";
}
}
HTML code:
Click here
<p>Total:<span id="count">0</span></p>
<button onclick="demo()">reset</button>
Is there a way to reset the variable to 0 in this code?
I've tried to reset the variable count to zero using document.getElementById() and adding =0; to the variable. Neither of these work. For example, if the user was to click the link the count would increase to 1. When they click the reset button it would appear to reset to 0 (unless using `var count=0;). However, if the user were to click the link again the count would be return the value 2, as it could simply continue to increment from the previous time.
I'm sorry if this has already been answered somewhere else, but it's very difficult to search for the terms = and ++.
You made it a local variable by using var
else {
var count=0;
alert("Reset.");
should be
else {
count=0;
alert("Reset.");
Two things:
Get rid of var where you reset the variable. That's giving you a separate local variable with the same name.
Using "count" as a variable name, if it's global, will cause problems if you've also got an element whose id is "count" in the DOM. Use a different variable name or a different id, or make sure that the variable is not global (can't tell from posted code).
The things you need to chnage in the code are:
And make the comparison to
if(parseInt(y) === 0) // You are converting it to integer and doing a strict check
the else construct to
else {
count = 0;
alert('Reset');
}

Trigger event not working or suspected passing on index

.full-arrow is an arrow that selects the next page. .full-navigation is a navigation bar, quite simply boxes in a line that change colour when you select them. The rest of the function isn't on here but you get the general idea.
When I create a trigger event to the function below the first one, it goes through okay but I'm unsure whether it's not picking up the index() or whether it's just not working at all. Weirdly, it works the first time but I think that's because the same_page variable is declared as 0 in the beginning.
The reason I'm also doubting whether it's the index() not being passed on is because the alert("foo"); isn't coming up.
$(".full-arrow").click(function() {
$(".full-navigation li:eq(" + same_page+1 + ")").trigger("click");
});
$(".full-navigation li").click(function(event) {
//alert("foo");
//alert(same_page);
same_page = $(this).index();
if(same_page == $(this).index()) { return false; }
});
Where are you getting the same_page variable from? Try using parseInt( same_page, 10 )--I have a hunch it's actually a string.

Categories

Resources