Problems with Countdown in JQuery - javascript

When I double click the card the dialog pops up, and it is then possible to create comments. So far so good. When creating the comments it is possible to edit it.
Then I want to have a countdown for the "edit" eg. after 3 sec the "edit" might be invisible for the user. So far so good.
The issue is, after closing the window or saving the data via button and opening the same card the edit appears again for 3 sec and so on.
I want when creating the comments, and after 3 sec the "edit" never appears again. Just like on this site.
Any idea how to implement this?
Live Demo
jQuery: Countdown,
// Set the timer to countdown
var sec = 3;
var timer = window.setInterval(function () {
sec--;
if (sec == -1) {
$('.edit').addClass('hidden');
clearInterval(timer);
}
}, 1000);
jQuery: Add comment,
function addComment(commentString) {
var container = $('#divComments');
var inputs = container.find('label');
var id = inputs.length + 1;
var data1 = {
commentString: commentString
};
var div = $('<div />', { class: 'CommentStyle' });
$('<label />', {
id: 'comment' + id,
for: 'comment' + id,
text: commentString
}).on('change', function () {
data1.commentString = $(this).text();
}).appendTo(div);
$('<br/>').appendTo(div);
var $Image = $('<img />',
{
"src": "/Pages/Images/alert.png",
"class": "CommentImage",
"for": "comment" + id
}).appendTo(container);
var d = new Date();
var $fulaDate = $('<div>' + d.getDate()
+ "-" + monthNames[d.getMonth()]
+ "-" + d.getFullYear()
+ "//" + d.getHours()
+ ":" + d.getMinutes()
+ '</div>').addClass('labelStyle').append(' ~').appendTo(div);
var $edit = $('<p />', {
class: 'edit',
for: 'comment' + id,
text: 'Edit'
}).append(' ~').appendTo(div);
var $delete = $('<p />', {
class: 'delete',
for: 'comment' + id,
text: 'Delete'
}).appendTo(div);
// Set the timer to countdown
var sec = 3;
var timer = window.setInterval(function () {
sec--;
if (sec == -1) {
$('.edit').addClass('hidden');
clearInterval(timer);
}
}, 1000);
div.appendTo(container).focus();
container.data('comments').push(data1);
}

EDIT
Please put this line after:
$.each($currentTarget.data('comments'), function (i, comment) {
addComment(comment.commentString);
});
$(".edit").each(function(){
$(this).addClass("hidden");
});
Rest all the lines should work fine. Try this solution. This may help you.

Related

Fire a AJAX request every second in AngularJS using $interval

The interval function keeps on looping in the last element that I click. What I want to happen is to cancel the last interval when I click on a new element and start all over again when I click it. I clicking on each item in ng-repeat.
This is my code.
$scope.onClickTab= function(x,tkid, sid, $event){
var vtpostdata = 'TokenId=' + tkid +
',SessionId=' + sid +
',ChatMessageCount=' + 0 +
',retrytimes=' + 10 +
',delayms=' + 100;
$interval(function() {
$http.jsonp(ServiceDomainSite + 'myApi' + vtpostdata + '?callback=JSON_CALLBACK&t='
+ new Date().getTime())
.success(function (data) {
var resultObject = angular.fromJson(data.Rows);
$scope.Chats = resultObject;
});
}, 1000);
};
Nice and fine with $interval.cancel(). I also removed var vtpostdata because it is not used in the code untill your $http request again. So there is no need to create a var at this point. Also check the documentation of AngularJS $interval to learn more about $interval handling.
var myInterval = null;
$scope.onClickTab = function(x,tkid, sid, $event){
//cancel current interval
if (myInterval !== null) {
$interval.cancel(myInterval);
}
myInterval = $interval(function() {
$http.jsonp(ServiceDomainSite + 'myApiTokenId=' + tkid +
',SessionId=' + sid +
',ChatMessageCount=' + 0 +
',retrytimes=' + 10 +
',delayms=' + 100 + '?callback=JSON_CALLBACK&t='
+ new Date().getTime()).success(function (data) {
var resultObject = angular.fromJson(data.Rows);
$scope.Chats = resultObject;
});
}, 1000);
};
$interval service returns a promise which can be canceled at any time so you can use them as per official documentation. For Eg.
var stopTime = $interval(function(){}, 1000);
and for canceling just use
$interval.cancel(stopTime);
https://docs.angularjs.org/api/ng/service/$interval

Appending a class to a javascript calendar given the data (clndr.js)

I am looking to assign a class to each clndr.js event that appears in my calendar based on the value itself. var temp shows an example of the data received. I want to the style each event on type being 1 or 2. The code shows the default template which I want to modify to simply add in the value passed in type as a class so I can then style it.
link to the source library on github
link to a similar problem on github
// This is the default calendar template. This can be overridden.
var clndrTemplate =
"<div class='clndr-controls'>" +
"<div class='clndr-control-button'>" +
"<span class='clndr-previous-button'>previous</span>" +
"</div>" +
"<div class='month'><%= month %> <%= year %></div>" +
"<div class='clndr-control-button rightalign'>" +
"<span class='clndr-next-button'>next</span>" +
"</div>" +
"</div>" +
"<table class='clndr-table' border='0' cellspacing='0' cellpadding='0'>" +
"<thead>" +
"<tr class='header-days'>" +
"<% for(var i = 0; i < daysOfTheWeek.length; i++) { %>" +
"<td class='header-day'><%= daysOfTheWeek[i] %></td>" +
"<% } %>" +
"</tr>" +
"</thead>" +
"<tbody>" +
"<% for(var i = 0; i < numberOfRows; i++){ %>" +
"<tr>" +
"<% for(var j = 0; j < 7; j++){ %>" +
"<% var d = j + i * 7; %>" +
"<td class='<%= days[d].classes %>'>" +
"<div class='day-contents <%= days[d].type %>'><%= days[d].day %></div>" +
"</td>" +
"<% } %>" +
"</tr>" +
"<% } %>" +
"</tbody>" +
"</table>";
var calendars = {};
$(document).ready(function () {
var thisMonth = moment().format('YYYY-MM');
var eventArray = {{ data|tojson }};
var temp = [{
date: thisMonth + '-22',
type: 1
}, {
date: thisMonth + '-27',
type: 2
}, {
date: thisMonth + '-13',
type: 1
}];
calendars.clndr1 = $('.cal1').clndr({
events: eventArray,
targets: {
day: 'day',
},
clickEvents: {
click: function (target) {
console.log('Cal-1 clicked: ', target);
},
today: function () {
console.log('Cal-1 today');
},
nextMonth: function () {
console.log('Cal-1 next month');
},
previousMonth: function () {
console.log('Cal-1 previous month');
},
onMonthChange: function () {
console.log('Cal-1 month changed');
},
nextYear: function () {
console.log('Cal-1 next year');
},
previousYear: function () {
console.log('Cal-1 previous year');
},
onYearChange: function () {
console.log('Cal-1 year changed');
},
nextInterval: function () {
console.log('Cal-1 next interval');
},
previousInterval: function () {
console.log('Cal-1 previous interval');
},
onIntervalChange: function () {
console.log('Cal-1 interval changed');
}
},
multiDayEvents: {
singleDay: 'date',
endDate: 'endDate',
startDate: 'startDate'
},
showAdjacentMonths: true,
adjacentDaysChangeMonth: false
});
// Bind all clndrs to the left and right arrow keys
$(document).keydown(function (e) {
// Left arrow
if (e.keyCode == 37) {
calendars.clndr1.back();
calendars.clndr2.back();
calendars.clndr3.back();
}
// Right arrow
if (e.keyCode == 39) {
calendars.clndr1.forward();
calendars.clndr2.forward();
calendars.clndr3.forward();
}
});
});
I don't know your code, so I'm working with the test of CLNDR from github - folder "tests".
Add at the bottom of test.js (basically just make sure it's after clndr activation)
var thisMonth = moment().format('YYYY-MM');
var temp = [{
date: thisMonth + '-22',
type: 1
}, {
date: thisMonth + '-27',
type: 2
}, {
date: thisMonth + '-13',
type: 1
}];
for (event of temp) {
$('.calendar-day-' + event.date).addClass('ev-type-' + event.type);
};
Then add some css styles to test.html <head> just to clearly see it's working
.ev-type-1 {
background: #F00 !important;
color: #fff !important;
}
.ev-type-2 {
background: #0F0 !important;
color: #fff !important;
}

Why my code removes a checkbox control on the first setInterval call

Why does the following code remove the checkbox control on the first setInterval call?
let autorefreshLabel = $('<label/>', {
text: 'Atuorefresh after ' + autorefreshTimer + ' seconds...'
});
let autorefreshCheckbox = $('<input/>', {
type: 'checkbox'
});
autorefreshLabel.prepend(autorefreshCheckbox);
$('#some-id').append(autorefreshLabel);
setInterval(function() {
autorefreshTimer -= 1;
autorefreshLabel.text('Atuorefresh after ' + autorefreshTimer + ' seconds...');
}, 1000);
Because that's what you've told it to do. You've put the checkbox inside the label, and in the setInterval callback you've used the text function to completely replace all contents of that label with the given text.
If you want to replace the text without replacing the checkbox, using jQuery the simplest thing is to use a span for the text:
let autorefreshLabel = $('<label/>', {
html: '<span>Atuorefresh after ' + autorefreshTimer + ' seconds...</span>'
});
let autorefreshCheckbox = $('<input/>', {
type: 'checkbox'
});
autorefreshLabel.prepend(autorefreshCheckbox);
$('#some-id').append(autorefreshLabel);
then in the callback:
autorefreshLabel.find("span").text(
'Autorefresh after ' + autorefreshTimer + ' seconds...'
);
Or you could put the checkbox back after removing it:
autorefreshLabel.find("span").text(
'Autorefresh after ' + autorefreshTimer + ' seconds...'
).prepend(autorefreshCheckbox);
The issue is because you set the text() of the label you created, which overwrites all the existing content of that element. You could use append() instead.
setInterval(function() {
autorefreshLabel.append('Autorefresh after ' + autorefreshTimer + ' seconds...');
}, 1000);
To avoid appending a new string on each iteration of the timer you could create another element within the label of which you can then set the text:
let autorefreshLabel = $('<label/>');
let autorefreshCheckbox = $('<input/>', {
type: 'checkbox'
}).appendTo(autorefreshLabel);
let autorefreshText = $('<span />').appendTo(autorefreshLabel);
$('#some-id').append(autorefreshLabel);
var autorefreshTimer = 100;
setInterval(function() {
autorefreshTimer -= 1;
autorefreshText.text('Autorefresh after ' + autorefreshTimer + ' seconds...');
}, 1000);
Working example

Problems with remove timestamps in JQuery

When I double click the card the dialog pops up, and it is then possible to create comments. So far so good. When creating the comments it is possible to delete it.
The issue is, that the timestamps can't be removed. The way I'm trying to remove the timestamps is by this line: $('.labelStyle').remove();
I want to be able to remove the timestamps, like the others elements but how?
Live Demo
JQuery: "click" handler
$('#divComments').on('click', '.delete', function (e) {
var uniqueval = $(this).attr("for")
var NameOfDataValue = $('label[for=' + uniqueval + ']').text();
$('img[for=' + uniqueval + ']').remove();
$('label[for=' + uniqueval + ']').remove();
$('p[for=' + uniqueval + ']').remove();
$('.labelStyle').remove();
var arr = $('#divComments').data('comments');
var theIndex = -1;
for (var i = 0; i < arr.length; i++) {
if (arr[i].commentString== NameOfDataValue) {
theIndex = i;
break;
}
}
if (theIndex == -1) {
alert("Error");
}
else {
$('#divComments').data("comments").splice(theIndex, 1);
}
});
JQuery: Add comment function
function addComment(commentString) {
var container = $('#divComments');
var inputs = container.find('label');
var id = inputs.length + 1;
var data1 = {
commentString: commentString
};
var div = $('<div />', { class: 'CommentStyle' });
$('<label />', {
id: 'comment' + id,
for: 'comment' + id,
text: commentString
}).on('change', function () {
data1.commentString = $(this).text();
}).appendTo(div);
$('<br/>').appendTo(div);
var $Image = $('<img />',
{
"src": "/Pages/Images/alert.png",
"class": "CommentImage",
"for": "comment" + id
}).appendTo(container);
var d = new Date();
var $fulaDate = $('<div>' + d.getDate()
+ "-" + monthNames[d.getMonth()]
+ "-" + d.getFullYear()
+ "//" + d.getHours()
+ ":" + d.getMinutes()
+ '</div>').addClass('labelStyle').append(' ~').appendTo(div);
var $edit = $('<p />', {
class: 'edit',
for: 'comment' + id,
text: 'Edit'
}).append(' ~').appendTo(div);
var $delete = $('<p />', {
class: 'delete',
for: 'comment' + id,
text: 'Delete'
}).appendTo(div);
div.appendTo(container).focus();
container.data('comments').push(data1);
}
You could do:
$(this).parent().find('.labelStyle').remove();
This will select the parent of the clicked button (.CommentStyle) then find the .labelStyle and remove it.

Button image change on a timer

In my project I have a page which contains 5 image buttons laying horizantally.
When the page loads image on the Button1 should change(remaining 4 buttons remains same).
After 3 seconds Button1 comes back to its original image and image on Button2 will change.
After 3 seconds Button2 comes back to its original image and image on Button3 will change.
And so on..
But After the Button5 is done , It should come back to the Button1 image again.
This should go on in a continuous loop.
Here is my code.But its not working I don't know the reason why its not working.
any help will be appreciated.
Here is my code
$(document).ready(function (){
BeginRotation();
});
function BeginRotation() {
rotateButton(0);
}
function rotateButton(buttonIndex) {
var previousIndex = (buttonIndex + 4) % 5;
var previousCurrentClass = 'main-nav-button' + (previousIndex + 1) + '-on';
var previousNewClass = 'main-nav-button' + (previousIndex + 1);
var currentClass = 'main-nav-button' + (buttonIndex + 1);
var newClass = 'main-nav-button' + (buttonIndex + 1) + '-on';
// alert('Previous Current Class: ' + previousCurrentClass + '\nPrevious New Class: ' + previousNewClass + '\nCurrent Class: ' + currentClass + '\nNew Class: ' + newClass);
$('.' + currentClass).removeClass(currentClass).addClass(newClass);
$('.' + previousCurrentClass).removeClass(previousCurrentClass).addClass(previousNewClass);
window.setTimeout(rotateButton((buttonIndex + 1) % 5), 3000);
}
One thing that is incorrect for sure
window.setTimeout(rotateButton((buttonIndex + 1) % 5), 3000);
It should be
window.setTimeout("rotateButton(" + ((buttonIndex + 1) % 5) + ")", 3000);
I didn't test this code, but something like this should work:
jQuery(function($){
var $btns = $('a.btn');
var index = 0;
setInterval(function() {
$btns.removeClass('rotateThis');
$btns[index].addClass('rotateThis');
index = (index + 1 >= $btns.size()) ? 0 : index + 1;
}, 3000);
});
$('a.btn') being whatever selector works to grab your image buttons of course.

Categories

Resources