Javascript/jQuery Click after Timer - javascript

I need to insert a timer and a click to the next page of my form after the timer counts down. Here's my form.
I believe I could implement something using either basic JS, or with jQuery (there's this jQuery plugin that looks promising.
For the prompt pages, I need a 30 second countdown, and for the form page immediately after I need a 5 minute countdown. How to implement JS and/or jQuery into Wordpress and/or Gravity Forms specifically?
I don't really have much code to start from, but this is what I've got so far:
$(document).ready(function () {
seconds = parseInt($("#countdown").attr('data-timelimit'));
var date = new Date();
date.setSeconds(date.getSeconds() + seconds);
$('#countdown').countdown({
date: date,
onEnd: goToNextPage,
render: function(date) {
return $(this.el).html(""+ (this.leadingZeros(date.min)) + " : " + (this.leadingZeros(date.sec)) + " sec");
}
});
$('#next_button').click(function (e) {
e.preventDefault();
e.stopPropagation();
goToNextPage();
});
I didn't make this code myself, so I'm not sure if it works, or if this is the right track either.

setTimeout should work for your usecase. Something like this will navigate to google.com in 30 seconds:
If the timeout amount is variable, you can use javascript to query the data attribute and replace 30000 with that variable.
setTimeout(function() {
window.location.href = 'https://google.com';
}, 30000);

If what you want is to programmatically click on your $('#next_button') button once the timer is up, try this. I haven't used countdown() but I suppose onEnd accepts an anonymous function
seconds = parseInt($("#countdown").attr('data-timelimit'));
var date = new Date();
date.setSeconds(date.getSeconds() + seconds);
$('#countdown').countdown({
date: date,
onEnd: function (){
$('#next_button').click();
},
render: function(date) {
return $(this.el).html(""+ (this.leadingZeros(date.min)) + " : " + (this.leadingZeros(date.sec)) + " sec");
}
});
$('#next_button').click(function (e) {
e.preventDefault();
e.stopPropagation();
goToNextPage();
});

Related

Bootstrap datepicker trigger change

I have from and to input fields with bootstrap date picker. When query params not empty I would like to change the value of these input fields and trigger the change date event on datepicker because I have a function that calculates total price between dates. When user selects dates from datepicker works fine but if I change the value by jquery it does not calculate.
$('#from').val('<%= #from_date %>').trigger( 'change' );
$('#to').val('<%= #to_date %>').trigger( 'change' );
//function
var dates_avail = new DatesAvailability({
start: '#from',
end: '#to'
});
..
W.DatesAvailability = function (opts) {
var options = $.extend({}, defaultOpts, opts);
var start = options.start + ',' + options.rel_start;
var end = options.end + ',' + options.rel_end;
$(start + ',' + end).datepicker({
autoclose: true,
format: "yyyy-mm-dd",
startDate: '+1d',
endDate: '+3y',
..
}).
on('changeDate', function (e) {
// I would like to trigger this.
..
I also have these lines in bootstrap-datepicker.js
..
if (fromArgs){
// setting date by clicking
this.setValue();
this.element.change();
}
else if (this.dates.length){
// setting date by typing
if (String(oldDates) !== String(this.dates) && fromArgs) {
this._trigger('changeDate');
this.element.change();
}
}
..
Try using the update mention in the documentation. Something like `$(start + ',' + end).datepicker('update', qParamStart);
If you're trying to figure out how to get the query params this is a good reference.
You can do this by manually calling the event changeDate.
E.g.
$('.datepicker').datepicker().trigger('changeDate');
I would do something like this.
$('.datepicker').datepicker('_trigger', 'changeDate');
This uses an undocumented private method, but will fire with event and the extra data you would expect.
Inspect the link from the calendar then call it conventionally. For me it was:
$('.ui-state-active').click();
or
$('.ui-datepicker-current-day').click();

Add 4 hours for current time in date time picker

How can I add 4 hours from my date-time pickers' startDate to endDate?
$(function() {
$('#startDate').datetimepicker();
$('#endDate').datetimepicker();
$("#startDate").on("dp.change", function(e) {
$('#endDate').data("DateTimePicker").setMinDate(e.date);
});
$("#endDate").on("dp.change", function(e) {
$('#startDate').data("DateTimePicker").setMaxDate(e.date);
});
});
Your e.date objects are instances of Moment. As you can see in the documentation, you can use the .add and .subtract functions on them:
$('#endDate').data("DateTimePicker").setMinDate(e.date.add(4, 'hours'));
// ...
$('#startDate').data("DateTimePicker").setMaxDate(e.date.subtract(4, 'hours'));
As for the comments:
To set the default date, use the defaultDate option. It works with both Moments and native Dates:
$('#startDate').datetimepicker({ defaultDate: Date() });
$('#endDate').datetimepicker({
defaultDate: $('#startDate').data("DateTimePicker").date().add(4, 'hours')
});
Also get rid of the dp.change event handlers, you don't need those callbacks just to set the default date. Unless of course you want to keep them linked, then use the dp.change but use the date function instead of the setMinDate and setMaxDate:
$("#startDate").on("dp.change", function(e) {
$('#endDate').data("DateTimePicker").date(e.date.add(4, 'hours'));
});
Beware an infinite loop if you want to link them like that both ways, calling date with a different date will trigger a new dp.change. While that shouldn't happen in your setup, it may start to if you tweak it slightly.
Have you tried this:
To add minutes:
$('#Start').data("DateTimePicker").date(e.date.add(30, 'minutes'));
To add hours:
$('#Start').data("DateTimePicker").date(e.date.add(4, 'hours'));
Also with below script, you can compare start and end date, and if they were equal or start date time was after end date time, you set your default date time again based on new selected date time by user, I always set the default date time on server side:
//Server side default setup for first run
Start = DateTime.Now;
End = DateTime.Now.AddMinutes(30);
And here is the js script:
<script type='text/javascript'>
$(function()
{
$('#Start').datetimepicker({
useCurrent: false //Important! See issue #1075
});
$('#End').datetimepicker({
useCurrent: false //Important! See issue #1075
});
$('#Start').on("dp.change",
function(e)
{
if (dateSorter($('#End').val(), $(this).val()) === -1 || dateSorter($('#End').val(), $(this).val()) === 0)
// if ($('#End').val() < $(this).val())
{
// console.log("End date "+$('#End').val()+ " is before start date: "+ $(this).val());
$('#End').data("DateTimePicker").date(e.date.add(30, 'minutes'));
}
// add your other scripts for example update something on the page, updateAvailableSeats();
});
$('#End').on("dp.change",
function(e)
{
if (dateSorter($('#Start').val(), $(this).val()) === 1 || dateSorter($('#Start').val(), $(this).val()) === 0)
// if ($('#Start').val() > $(this).val())
{
// console.log("Start date " + $('#Start').val() + " is after end date: " + $(this).val());
$(this).data("DateTimePicker").date(e.date.add(30, 'minutes'));
}
});
// updateAvailableSeats();
});
Hope this helps.
Thanks

How to clear all instances of a setInterval?

I've always had issues with setInterval:
$('li.item').live('click', function(){
//Need to work with Dyn created object
//clearInterval(itemClockInterval);
itemClockInterval = setInterval(function() {
deconInterval(_this.children('.timeleft'), time);
}, 1000);
});
There are multiple li's with the class "item". When clicked, the setInterval function updates a clock appended to that specific li.
My problem is that every time an li is clicked, the clock counts down twice as fast as before because an additional interval is running. I need all instances of the interval to be cleared before the new interval starts, but none of my solutions work.
I commented out one of the things I have tried, seeing as though the interval is not created until later this is problematic.
Store the result of setInterval() on the element using .data() and clear it on click.
$('li.item').live('click', function(){
$this = $(this);
var existing_timer = $this.data('clock');
if (existing_timer){
clearInterval(existing_timer);
}
    itemClockInterval = setInterval(function() {
        deconInterval($this.children('.timeleft'), time);
    }, 1000);
$this.data('clock', itemClockInterval);
});
use a closure:
$('li.item').live('click', (function(){ //Need to work with Dyn created object
var itemClockInterval;
return function(){
if(itemClockInterval) clearInterval(itemClockInterval);
itemClockInterval = setInterval(function() {
deconInterval(_this.children('.timeleft'), time);
}, 1000);
};
})());
OR, use jQuery's data method:
$('li.item').live('click', function(ev){ //Need to work with Dyn created object
var itemClockInterval = $(ev.target).data("itemClockInterval")
if(itemClockInterval) clearInterval(itemClockInterval);
$(ev.target).data("itemClockInterval", setInterval(function() {
deconInterval(_this.children('.timeleft'), time);
}, 1000));
});
Use data to store the intervalID associated with that li...
$('li.item').live('click', function(){ //Need to work with Dyn created object
var itemClockIntervalID = $(this).data("itemClockIntervalID");
if (itemClockIntervalID != "undefined") {
clearInterval(itemClockIntervalID);
}
itemClockIntervalID = setInterval(function() { deconInterval(_this.children('.timeleft'), time); }, 1000);
$(this).data("itemClockIntervalID", itemClockIntervalID);
});
Or use jQuery's ability to keep track of the timers for you as described here: http://plugins.jquery.com/project/timers. It automatically maintains an association between a jQuery object and your timer so it keeps track of the previous timer so you can clear the interval before setting a new one.

avoid repeating same code for each item with jquery

I have the following inline javascript, im using a jquery countdown plugin to display time remaining.
this code exists with each "Comment" on the page, hence it is repeating multiple time on the page. How can I make this external? and avoid the repetition?
im using .nt mvc razor and attaching id.
<script type="text/javascript">
$(function () {
var dateLeft = new Date(#(item.UnixTicks));
$('#countdown-#(item.ID)').countdown({until: dateLeft, format:'MS', onExpiry: liftOff, onTick: watchCountdown});
function liftOff() {
alert('We have lift off!');
}
function watchCountdown(periods) {
$('#monitor-#(item.ID)').text('Just ' + periods[5] + ' minutes and ' +
periods[6] + ' seconds to go');
}
});
</script>
You can put the UnixTicks into an attribute in the comment, give all of the comments a class="comment", and loop over them:
$('.Comment').each(function() {
var dateLeft = new Date(parseInt($(this).attr('data-unixticks'), 10));
...
});

Javascript timer that restarts on key up?

O, so i have a 'live search' ajax search, which currently runs an sql search (via ajax) on each key up.
What i would prefer is to:
run an sql search after a key has not been pressed for say 800 milliseconds
.
So i want to have a timer that is started on key up,
if the timer reaches 800ms then the ajax is called,
if a new keyup event occurs the timer is restarted
how would i do this?
(function () {
var theTimeout;
function doSearch() {
// Do Search
};
$('#theField').bind('keyup', function () {
clearTimeout(theTimeout);
theTimeout = setTimeout(doSearch, 800);
});
}())
There's an excellent plugin TypeWatch you may take a look at (IIRC StackOverflow uses this for the Users page). Here's a sample usage:
$("#textId").typeWatch({
highlight: true,
wait: 800,
captureLength: -1,
callback: function() {
// changed text
}
});
I had that problem my solution was this:
var doAjax = 0
$("input#name").keyup(function(){
doAjax++;
setTimeout(function(){
doAjax--;
if(doAjax>=1){
return;
}
$.post("do_ajax", { ...
dunno if it is the best solution, but it works :)

Categories