I have a function counting characters correctly.. on key up and key down eventes
but i am echoing the value from the database so when the page will load there will already be some text on load window. I am not able to count the character as soon as page loads. Can any one help me out ?
Here is my javascript that deals with character count limit is 50
function textCounter(textField, showCountField) {
var maxAmount = 50;
if (textField.value.length > maxAmount) {
textField.value = textField.value.substring(0, maxAmount);
} else {
showCountField.value = maxAmount - textField.value.length;
}
}
Thanks for your help
Use
window.load = function() {
textCounter(document.getElementById( textfieldId), document.getElementById( showCountFieldID) );
}
use
<body onload "textCounter(par1,par2)"> // replace with pweameters
Related
Please, I am trying to link all my pages with progressive 30 seconds count timer using JavaScript and html without being recount on page navigation. Thanks!
With more information in mind from comments, here's your code:
Somewhere in index.html
<div id="counter"></div>
YourScript.js
// Simplifies getting the value of a cookie
function getCookie(name)
{
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
}
// Max time for cookie
var count = 30;
if(document.cookie && document.cookie.match('counter')) {
// Set value of counter to match the cookie
count = getCookie('counter');
}
// Runs once per second
setInterval(function() {
// Decrease the value of count by 1 every second
count--;
// if count is less or equal to 0 we move to menu.html
if(count <= 0) {
window.location.href="menu.html"
}
// Set the text inside the <div id="counter"></div> to the value of counter
document.getElementById('counter').innerHTML = count;
// Set the value of the cookie to match the value of our counter variable
document.cookie = 'counter=' + count;
}, 1000);
I created a jsfiddle for this but for some reason jsfiddle doesn't want to create a unique URL for me right now... Go to jsfiddle.net and copy paste this into the script field, and the div into the html area, then press Run several times and you'll see that the counter keeps counting down, persisting between page refreshes.
Very much a newbie here and wanting a bit of guidance.
I'm trying to create a project where you bind a key to start a timer then show an output in the results box. However i'm facing an issue where I need to create a new line if the user releases the bound button to start a new timer, however I can't find a way to start the timer again. Bear in mind within the time, a user could press the bound key over a hundred times, I don't want to manually create new lines and timer's.
My thoughts are creating a a random token, then on release, it creates a break, if the next line doesn't match this token it begins again.
Edit:So you can see, the value is based on the 2 variables, and even when I hold down the specific button again, it just adds to the current smallTime. I know this is how it's currently build, but i'm trying to get it to reset and go to the next line dynamically.
Any help would be greatly appreciated.
<html>
<head>
<textarea class="code_input" name="allInputs" id="textareaCode" wrap="logical" rows="10" cols="50" readonly="true"> </textarea>
<script type="text/javascript">
var shortSeconds = 0;
var shortmillisec = 0;
function buttonPressed(e) {
key = String.fromCharCode(e.keyCode).toLocaleLowerCase()
//alert (key)
keyInput = e.keyCode
if (withinTime == true && key == bind) {
shortDisplay()
shortTimerFunction();
}
}
function shortDisplay() {
if (shortmillisec >= 9) {
shortmillisec = 0
shortSeconds += 1
}
else
shortmillisec += 1
}
function startstoptimerShort() {
if (shortTimer > 0) {
clearTimeout(shortTimer);
shortTimer = 0;
} else {
withinTime = true
shortTimerFunction()
}
}
function shortTimerFunction() {
smallTime = shortSeconds + "." + shortmillisec;
shortTimer = setTimeout("shortTimerFunction()", 100);
//need to work out what line to put the output on
allInputs = document.getElementById('textareaCode')
allInputs.value = (textbox3.value) + (": " + smallTime) + '\n';
}
</script>
</body>
</html>
I'm making a webpage where user events are logged in.
To test the feature I made a small, independant webpage with a teaxtarea and a text input. The events logged are those performed on the input element.
I want to prevent the same event text to be shown multiple times in a row, but I can't seem to prevent them from showing up!
I also want to add a line to separate event groups 0.5 seconds after no other event happened, but the line seems to appear on every event trigger, evenif I use clearTimeout with the timeout ID.
Basically: I don't want any line to be repeated. If the last line is a separator line, then it must not add another one. Yet it doesn't see to work.
JSFiddle Demo
Here is my code:
JavaScript
var timerID = 0;
function addSeparateLine()
{
document.getElementById('listeEvenements').value += "--------------------\n";
}
function show(newEventText)
{
var eventListField = document.getElementById('listeEvenements');
var eventList = [];
if (eventListField.value.length > 0)
{
eventList = eventListField.value.split("\n");
}
var eventCounter = eventList.length;
if (eventList[eventCounter - 2] == newEventText)
{
clearTimeout(timerID);
newEventText = "";
}
timerID = setTimeout(addSeparateLine, 500);
if (newEventText !== "")
{
eventListField.value += newEventText + "\n";
}
return true;
}
HTML
<fieldset id="conteneurLogEvenements">
<legend>Events called from HTML attribute</legend>
<textarea id="listeEvenements" rows="25"></textarea>
<input id="controleEcoute" type="text" onBlur="show('Blur');" onchange="show('Change');" onclick="show('Click');" onfocus="show('Focus');" onMousedown="show('MouseDown');" onMousemove="show('MouseMove');" onMouseover="show('MouseOver');" onkeydown="show('KeyDown');"
onkeypress="show('KeyPress');" onkeyup="show('KeyUp');" />
</fieldset>
http://jsfiddle.net/z6kb4/2/
It sounds like what you want is a line that prints after 500 milliseconds of inactivity, but what your code currently says to do is "print a line 500 milliseconds after any action, unless it gets canceled". You can get better results by structuring the code more closely to your intended goal.
Specifically, instead of scheduling a new timeout every time an event occurs, simply start a loop when the first event occurs that checks the time that has elapsed since the most recent event received and then prints a line when the elapsed time exceeds the desired threshold (500 milliseconds). Something like:
function addSeparateLine() {
var elapsed = new Date().getTime() - lastEventTime;
if (elapsed >= 500) {
document.getElementById('listeEvenements').value += "--------------------\n";
clearInterval(timerID);
timerID = -1;
}
}
...and then you schedule it like:
if(newEventText !== "") {
lastEventTime = new Date().getTime();
eventListField.value += newEventText+"\n";
if (timerID == -1) {
timerID = setInterval(addSeparateLine,100);
}
}
Working example here: http://jsfiddle.net/z6kb4/4/
Because you are not actually stopping the show function in any way. The clearTimeout only applies to the separator add. I have updated your fiddle. You need to wrap your function with
if (+new Date() - lastfire < 500) return;
and
lastfire = +new Date();
(before the last return--see the updated fiddle). Also, make sure to stick the global definition var lastfire = -1; somewhere up top.
First of all, I know my question seems to be already asked many many times but I'm facing a weird issue.
Here's the situation :
I've got an integer (dynamically loaded) in this tag :
<i id="my_id">{{here's my integer}}</i>
What I want to do is to retrieve the integer inside my tag but this integer is set to 0 at first (When the page isn't fully loaded") and then 2 or 3 seconds later, this integer is set to its real value.
So I tried something like this :
var test = 0;
$('#my_id').change(function(){
test = $('#my_id').html();
});
console.log(test);
This always returns me 0. I tried many things to get the current value of my tag but I can't find a way to succeed. Can you please help me get this integer ?
Cordially, Rob.
The change event is only fired by input elements. You can try polling the value like so:
var intervalId = setInterval(function() {
var value = parseInt($('#my_id').text(), 10);
if(value > 0) {
clearInterval(intervalId);
//... do stuff
}
}, 250); //poll every 250ms
Another way is to fire a custom event when you change the value:
//Somewhere in your code where you set the value in the i tag:
$('#my_id').text(value);
$('#my_id').trigger("valueChanged");
//Elsewhere in your code
$('#my_id').on("valueChanged", function() {
var value = parseInt($(this).text(), 10);
if(value > 0) {
//... do stuff
}
});
I am aware that when coding an extension, there is no way we can delay a function call except for using a setTimeout call but here's what I am trying to achieve in a plugin that I am developing for Firefox (this is not for Javascript embedded into a web page by the way):
for (var i = 0; i < t.length ; i++) {
//Load a URL from an array
//On document complete, get some data
}
The idea is simple. I have an array of URLs that I want to parse and extract some data out of. Each of these URLs take some time to load. So, if I try to get some data from the current page without waiting for the page to load, I will get an error. Now, the only way to do this as I know is as follows:
firstfunction: function() {
//Load the first url
setTimeout("secondfunction", 5000);
}
secondfunction: function() {
//Load the second url
setTimeout("thirdfunction", 5000);
}
And so on... I know this is obviously wrong.. I was just wondering how people achieve this in Javascript...
EDIT: Sorry about not being more detailed...
I'm not convinced that this type of foolery is necessary but I'm not an extension dev so who knows. If this is the approach you want, then just have the setTimeout call refer to the same function:
var index;
firstfunction: function() {
// do something with `index` and increment it when you're done
// check again in a few seconds (`index` is persisted between calls to this)
setTimeout("firstfunction", 5000);
}
I am not sure how to do this from a plugin, but what I've done with iframes in the past is attach a callback to the target document's onLoad event.
Maybe something like:
var index = 0;
var urls = [ ..... ];
function ProcessDocument() { ....; LoadNextDocument(); }
function LoadNextDocument() { index++; /* Load urls[index] */; }
document.body.onLoad = ProcessDocument;
Somewhere in there you'd need to test for index > urls.length too for your end condition.
I had same problem but I used recursion instead of looping.
Below is the running code which changes the innerHTML of an element by looping through the list. Hope its helpful.
<Script type="text/javascript">
var l;
var a;
function call2()
{
l = document.getElementById('listhere').innerHTML;
a = l.split(",");
call1(0);
}
function call1(counter)
{
if(a.length > counter)
{
document.getElementById('here').innerHTML = a[counter];
counter++;
setTimeout("call1("+counter+")",2000);
}
}
</Script>
<body onload="call2()">
<span id="listhere">3,5,2,8</span><Br />
<span id="here">here</span>