Sorry, i am not sure if I am asking the question correctly. When a date is changed by a user the date count down changes on the page. If the date is changed more than once it flashes all date changes. I guess it is storing the previous information somewhere. I have tried clearing the vars.
var deal_yeax = '';
as I would do in php with no luck
$('#deal_end').focusout(function() {
var deal_end = $("#deal_end").val();
var array = deal_end .split('-');
var deal_montx = array[0];
var deal_dax = array[1];
var deal_yeax = array[2];
deal_montx = deal_montx - 1;
$(function(){
ts = new Date(deal_yeax , deal_montx , deal_dax );
$(".h").countdown({
timestamp : ts,
callback : function(days, hours, minutes, seconds){
message_days = (days);
var message_hours = (hours);
$(".message_hours").text(message_hours + " Hours");
var message_minutes = (minutes);
$(".message_minutes").text(message_minutes + " Minutes");
var message_seconds = (seconds);
// Creat the display
if ( message_days < 1 && message_hours < 1 ) { $(".message_seconds").text(message_seconds + " Seconds"); }
else if ( message_days < 1 && message_hours > 1 ) { }
else if ( message_days == 1 ) { $(".message_days").text(message_days + " Day"); }
else { $(".message_days").text(message_days + " Days"); }
if ( message_days < 1 && message_hours < 1 && message_minutes < 1 && seconds < 1 ) {
$(".hide_my_buy_button").fadeOut("fast");
}
}
});
});
});
Everytime you "focusout" from #deal_end, you'll attach a countdown event to .h. Without knowing exactly how countdown(...) works (It'll be good if you provide the source so we can provide more help!), one way to fix the issue maybe to use JQuery's unbind(...) function to remove existing listeners on an event before adding a new one to it.
Here's an example on the issue:
<!-- HTML -->
<div>
<input id="text" />
<button id="clicker" />
</div>
<!-- Javascript -->
$('#text').focusout(function() {
var text = this.value;
// Everytime #text is "focused out", a new event is registered with #clicker.
$('#clicker').click(function() {
console.log('Value: ' + text);
});
});
... and here's how to solve the issue (It's just one of the many ways. This way is probably not the most elegant but anyhow.)
$('#text').focusout(function() {
var text = this.value;
$('#clicker').unbind('click');
// Everytime #text is "focused out", a new event is registered with #clicker.
$('#clicker').click(function() {
console.log('Value: ' + text);
});
});
Bottom line: It seems focusout(...) is adding a new countdown everytime it is triggered. That might be the problem you're having.
Not sure if this helps? Lemme know.
P.S. JSFiddle to go with it: http://jsfiddle.net/PE9eW/
The problem seems to be with .countdown function that you are using in your code to flash the date changes. When you assign a new count down object to $(".h") the plugin or the function probably assign some event handler or interval to it, but it doesn't seem to clear the old ones when it is called again and that is why it flashing all the dates for each countdown. So you will have to do it manually. I am not sure if you are using an external plugin or is it your own function but what you need to do is to clear the existing events or intervals that is assigned to your element when you call the function. I can be more helpful if you tell me which plugin you are using or maybe show the code if it is your own function. (referring to .countdown() )
Related
I'm writing a choose your own adventure program where If a specific option is chosen (example to wait) the user gets a random number between 1-10 to do push ups(the push-ups would be the user clicking on the prompt "ok" button however many times the random number is equal to) here's my code so far but I keep getting errors. I'm a complete noob so go easy on me.
var count = Math.floor((Math.random() * 10) + 1);
var setsOf10 = false;
function pushUps() {
alert("Nice! Lets see you crank out " + pushUps + "!");
}
if (setsOf10 == pushUp) {
alert("Nice! Lets see you crank out " + pushUp + "!");
setsOf10 = true;
}
for (var i=0; i<count; i++){
pushUps();
}
else {
alert("Really, thats it? Try again");
}
while ( setsOf10 == false);
}
After playing with this some more I can tell i'm close but still don't have it. and again, I'M NOT ASKING YOU TO SOLVE THIS FOR ME JUST NEED POINTERS AS TO WHAT IM DOING WRONG OR MISSING. Here's what I have, Its giving me my random number I just need it to allow me to click the "ok" button however many times the random number has assigned me.
var pushUpSets = Math.floor((Math.random() * 10) + 1);
function pushUps(){
alert(pushUpSets);
if (pushUpSets < 3){
var weak = "Thats it? Weak sauce!";
alert(weak);
}
else{
alert("Sweet lets get some reps in!");
}
for (i=0; i>3; i++){
pushUps(pushUpSets);
}
}
Here, the make a choice button is just dummy to allow us to go to do push ups. Each click decrements our count.
// This is important, we use this event to wait and let the HTML (DOM) load
// before we go ahead and code.
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('#choice').addEventListener('click', makeChoice);
});
function makeChoice() {
// Call a method to set random pushups and setup the click event
setUpPushUp();
// Here we change the display style of the push up section so that it shows to the player.
document.querySelector('.activity').style.display = 'block';
}
// The pushups variable is declared at the document level
// This way our setUpPushUp and doPushUp functions have easy access.
let pushUps = 0;
function setUpPushUp() {
// Create a random number of pushups, in sets of 10.
// We add an extra 1 so we can call the doPushUp method to initialize.
pushUps = (Math.floor((Math.random() * 10)+1)*10)+1 ;
// Add a click event to the push up button and call our doPushUp method on each click.
document.querySelector('#push').addEventListener('click', doPushUp);
// This is just an init call, it will use the extra 1 we added and place test in our P tag.
doPushUp();
}
function doPushUp() {
// Get a reference to our output element, we will put text to player here.
let result = document.querySelector('p');
// They have clicked, so remove a push up.
pushUps--;
// See if the player has done all the required push ups (i.e. pushUps is 0 or less.)
if (pushUps > 0) {
result.innerText = `You need to crank out ${pushUps} pushUps`;
} else {
result.innerText = 'Nice work!';
}
}
.activity {
display: none;
}
<button id="choice">Make a choice !</button>
<div class="activity">
<p></p>
<button id="push">Push</button>
</div>
I use fullcalendar js jquery plugin which is a great plugin but I have a small question do you know how:
I have a list of events which always not overlap.
Then sometimes I need to resize an event to be 1 or 2 hours much longer. The real step is here I try to make the next event to be not overlap but to move according to the resized end event. I have tried with event overlap custom function but it doesn't really work. There is always a gap of minutes between the two events.
I will send you a fiddle tomorrow to show you where I am.
/EDIT/
Just Create this Codepen :
http://codepen.io/cchumi/pen/pEGLXd
Javascript example for overlap :
eventOverlap: function(stillEvent, movingEvent) {
//Update MovingEvent
$('#calendar').fullCalendar('updateEvent', movingEvent);
//swap stillEvent time with movingEvent
stillEvent.end = stillEvent.end;
stillEvent.start = movingEvent.end;
//Update stillEvent
$('#calendar').fullCalendar('updateEvent', stillEvent);
//return true to allow swap.
return true;
}
it's been a while since your post but I think that I got a solution for you, I was looking your code and understood that, at the moment that the events overlaps the eventoverlap function is triggered, so I just add an event listener .mouseup() before your code to stop the trigger of your code until you release the click of the mouse. Now it works perfectly.
Now your code has to look like this:
eventOverlap: function(stillEvent, movingEvent) {
$('#calendar').mouseup(function() {
var movingEventEnd = moment(movingEvent.end).utc().format();
//"YYYY-MM-DDTHH:mm:ss"
var StillStart = moment(stillEvent.start).utc().format();
var StillEnd = moment(stillEvent.end).utc().format();
var duration = moment.duration(moment(StillEnd).diff(moment(StillStart)));
var hoursbaseStillEvent = duration.asHours();
console.log("Still Hours Base " + hoursbaseStillEvent);
$('#calendar').fullCalendar('updateEvent', movingEvent);
var movingEventNewEnd = moment(movingEvent.end).utc().format();
var durationMovingEvent =
moment.duration(moment(movingEventNewEnd).diff(moment(movingEventEnd)));
var hoursMovingEvent = durationMovingEvent.asHours();
console.log("hourss " + hoursMovingEvent);
stillEvent.start = moment(movingEvent.end).utc().format();
var StillEventStart = moment(stillEvent.start).utc().format();
console.log("StillEventStart " + StillEventStart);
var StillEventEnd = moment(stillEvent.end).utc().format();
var Startdate = moment(StillEventStart).utc().format();
console.log("Startdate " + moment(Startdate).utc().format());
var Enddate = moment(StillEventEnd);
var StillEventEndNew = moment(Startdate).add(hoursbaseStillEvent, 'hours');
console.log("StillEventEndNew " + moment(StillEventEndNew).utc().format());
stillEvent.end = moment(StillEventEndNew).utc().format();
$('#calendar').fullCalendar('updateEvent', stillEvent);
});
return true;
//return stillEvent.allDay && movingEvent.allDay;
},
I wrote simple monitor which check few things on my networks and display status - I am fetching statuses using ajax.
When something is wrong I am adding class error to div which is displaying current status.
Later I add player with error sound when class error is present it plays music. I set 3 second interval and thats all.
But not always error mean error, sometimes I recive false warning.
Now I am looking for way to play sound when class error exists longer than XX seconds.
I suppose I have to wrote function with interval 1s, add every hit 1 to temp variable and check is variable bigger than else clean temp variable, but maybe is there more elegant way.
i guess it should work
$('.error').each(function(){
var e = $(this)
setTimeout(function(){
if (e.attr('class') == 'error'){
e.attr('class','error-with-sound');
}
},2000);
});
You should take two vars store the current time at their respective events.
var oldTime, newTime;
// Now when you are adding the class
$(something).addClass("someclass");
oldTime = new Date().getTime(); // Store the timestamp.
//And when you are removing the class
$(something).removeClass("someclass");
newTime = new Date().getTime(); // Store the timestamp.
// Now you check whether class was added for more then XX Seconds
var _diff = (newTime - oldTime)/1000; // Diference is in seconds.
There is no direct way for that, you can add timestamps in your class with separator something like error_1448953716457 and later you can split that and can compare with current timestamps
$('#na').click(function () {
var t = new Date().getTime();
$('h1').addClass("error_" + t);
});
$('#nr').click(function () {
var t = new Date().getTime();
$("[class^=error]").each(function (e) {
$("span").html("Diff. Seconds : " + ((t - ($(this).attr('class').split(' ').pop().split('_')[1])) / 1000).toString());
});
});
input {
width:100px;
}
.error {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<h1>.addClass()</h1>
<input id="na" value="Add Class1" type="button" />
<br/>
<input id="nr" value="Calculate Diff" type="button" />
<span></span>
If you want to track .error elements on the page, set an independent interval that looks for those elements and tracks the ones it has seen before by setting an attribute or data value in jquery.
Remember to clearInterval(interval) if you no longer need to check for .error elements.
(function ($) {
// set constants in milliseconds as desired
var INTERVAL_LENGTH = 100, // how often to check DOM for error elements
NOTIFY_AFTER = 3000; // handle error after this length
// check for .error elements and handle those that have been around for a while
var interval = setInterval(function () {
var now = Date.now();
$(".error").each(function () {
var t = $(this).data('error-time');
if(t) {
if(now - t > NOTIFY_AFTER) {
handleErrorElement(this);
}
}
else {
$(this).data('error-time', now);
}
});
}, INTERVAL_LENGTH);
function handleErrorElement(elem) {
// do what you need for error elements visible past a threshold
console.log("handling error element: ", elem);
}
})(jQuery);
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.