Add class to div in jQuery based on a date - javascript

I admit not being so great with JavaScript.
I've been tasked to build a utility that will run a check to see if a campaign date is going to expire in 2 weeks or less and add a class if it's going to.
The date is coming from a service and it's built (datatables map) as follows.
The data is coming back undefined but that's a different issue.
Any feedback would be greatly appreciated because I don't seem to be having any luck whatsoever.
Initially I had a date object in there but wasn't sure it was necessary.
/*HTML Rendered Out for that table cell (there are multiple but this is how it
comes out*/
<td class=" campaign_start_date small-screen small-screen-2-col">06/14/2017 -
<div class="campaign-end-date">06/29/2017</div></td>
JS
//Datatables Code & modified for our project
{title:ax.L(114), class:'campaign_start_date small-screen small-screen-2-col', data:function(row, type, val, meta) {
var campaignEndDate = ax.Utils.deNull(row.campaign_end_date, '');
campaignEndDate = ax.Utils.RFCFormat(campaignEndDate, { excludeTime: true });
var campaignStartDate = ax.Utils.deNull(row.campaign_start_date, '');
campaignStartDate = ax.Utils.RFCFormat(campaignStartDate, { excludeTime: true });
var campaignDateString;
if (campaignEndDate && campaignStartDate ) {
campaignDateString = campaignStartDate + ' - ' + '<div class="campaign-end-date">' + ax.Utils.campaignEndDateAlert(campaignEndDate) + '</div>';
} else {
if (!campaignEndDate && campaignStartDate) {
campaignDateString = campaignStartDate + ' - ? ';
}
else if (!campaignStartDate && campaignEndDate) {
campaignDateString = ' ? - ' + campaignEndDate;
}
else {
campaignDateString = ' ';
}
}
return campaignDateString
//My attempt at doing this from the Utility file - the code that i'm having no luck with.
publicMethods.campaignEndDateAlert = function (data) {
var campaignDateEnd = data.campaign_end_date;
var $orderTable = $('#order-table');
var $campaignDate = $orderTable.find('.campaign-end-date')
if (campaignDateEnd <= campaignDateEnd + 86400000) {
$campaignDate.addClass('green');
}
}

Related

Refreshing / Cycling through a parsed RSS feed every 5 mins

I am working on a monitor signage display and have a "welcome to RSS" feed with just a title and desc. I have code from feedEk that's been tweaked a bit to parse the feed and cycle it so I only have one title and desc. showing at a time. This feed could be added to or deleted info at any time so I need it to refresh every five mins. I've tried several solutions on here and just can't seem to work it out.
Here is the adjusted FeedEk code with comments on the adjustments:
(function (e) {
e.fn.FeedEk = function (t) {
var n = {
FeedUrl: "http://myrss.com/",
MaxCount: 1,
ShowDesc: true,
ShowPubDate: false,
CharacterLimit: 100,
TitleLinkTarget: "_self",
iterate: false
};
if (t) {
e.extend(n, t)
}
var r = e(this).attr("id");
var i;
processFeedData = function (t) {
//This just makes it flash too much
//e("#" + r).empty();
var s = "";
en = t.responseData.feed.entries;
if (n.iterate == true) {
//Setting a variable to store current item
i = window.feedcur = typeof(window.feedcur) === 'undefined' ? 0 : window.feedcur;
t = en[i];
s = makeString(t);
//incrementing the current for the next time we loop through
window.feedcur = ((i+1)%en.length);
} else {
for (i=0;i<en.length;i++) {
t = en[i];
s += makeString(t);
}
}
//Changing this to just replace what was there (less blinky feeling)
e("#" + r).html('<ul class="feedEkListSm">' + s + "</ul>");
}
makeString = function (t) {
s = '<li><div class="itemTitleSm"><a href="' + t.link + '" target="' + n.TitleLinkTarget + '" >' + t.title + "</a></div><br>";
if (n.ShowPubDate) {
i = new Date(t.publishedDate);
s += '<div class="itemDateSm">' + i.toLocaleDateString() + "</div>"
}
if (n.ShowDesc) {
if (n.DescCharacterLimit > 0 && t.content.length > n.DescCharacterLimit) {
s += '<div class="itemContentSm">' + t.content.substr(0, n.DescCharacterLimit) + "...</div>"
} else {
s += '<div class="itemContentSm">' + t.content + "</div>"
}
}
return s;
}
if (typeof(window.feedContent) === 'undefined') {
e("#" + r).empty().append('<div style="padding:3px;"><img src="loader.gif" /></div>');
e.ajax({
url: "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=" + n.MaxCount + "&output=json&q=" + encodeURIComponent(n.FeedUrl) + "&hl=en&callback=?",
dataType: "json",
success: function (t) {
window.feedContent = t;
processFeedData(window.feedContent);
}
});
} else {
processFeedData(window.feedContent);
}
}
})(jQuery)
On the php page I have the following code which cycles through on an interval. I've tried wrapping this into another function that refreshes it but that didn't work. I've also tried just refreshing the page, but that just makes the whole page blink and still doesn't refresh the feed. It seems to refresh every 12 to 24 hours.
<!-- this is for the rss feed -->
<script type="text/javascript" >
$(document).ready(function () {
feedsettings = {
FeedUrl: 'http://myrss.com/',
MaxCount: 100,
ShowDesc: true,
ShowPubDate: false,
DescCharacterLimit: 100,
iterate: true
}
$('#divRss').FeedEk(feedsettings);
setInterval(function(){
$('#divRss').FeedEk(feedsettings);
},7000);
});
</script>
<style>
.rssDiv{float:right; padding-left:35px;}
ul{width:500px !important}
</style>
<!-- end feed stuffs -->
Any help guidance assistance or direction is immensely appreciated. I have to make this self sustaining with little to no extra installations. I've also posted this on code review but I think that may have been the wrong place to post this initially.

Having some code inside setInterval execute only once

I have a setInterval call inside my Javascript which checks if there are new notifications for the user. This interval makes an AJAX call and updates the DOM based on the response. This interval is set to repeat every 10 seconds.
There is a little box that needs to popup if there are new notifications and it is inside this interval. In the current code, this box shows up every 10 seconds if there are new notifications that are not marked as seen and that's pretty annoying.
Is there a way to make this little box appear only once per notification set? So for example there are X new notification and after 10 seconds this number didn't change, don't show this box. How do I achieve this? I'm stuck here.
This is how my interval code looks like:
setInterval(function(){
$.get(generate_site_url() + 'user.php?action=get_notifications', function(data) {
response = $.parseJSON(data);
if ('error' in response)
{
return;
}
if (response.notification_array.length == 0)
{
return;
}
$('.user-notification').text(response.notification_count);
$('.no-notes').hide();
var notificationStr = '';
for (var key in response.notification_array)
{
var notification = response.notification_array[key];
var notificationHTML = '<li' + ((notification.notification_seen == false) ? ' style="background: #fffaf1;"' : '') + '>';
notificationHTML += '<a href="' + notification.notification_target + '" id="nid-' + notification.notification_id + '">';
notificationHTML += '<span class="glyphicon glyphicon-' + ((notification.notification_type == 'like') ? 'thumbs-up' : (notification.notification_type == 'dislike') ? 'thumbs-down' : (notification.notification_type == 'favorite') ? 'heart' : 'bell') + '"></span> ';
notificationHTML += notification.notification_message;
notificationHTML += '</a></li>';
notificationStr += notification.notification_message + '<br />';
$('.notifications-dropdown').prepend($(notificationHTML));
}
display_alert(notificationStr, 'danger', 5000, 'bottom'); // This shows the box
});
}, 10000);
I'll expand my original comment answer here.
Set a variable accessible outside the interval function, in which you track the last count of new notifications. Next time the interval runs, compare the counts and check if there are any new ones.
var lastNewMessageCount = 0;
setInterval(function(){
// ajax stuff
if( response.notification_array.length > lastNewMessageCount ){
// show notices
}
lastNewMessageCount = response.notification_array.length;
});
Try making a global Array, then adding a conditional if(response.notification_array.length > nameOfGlobalArray.length) before the execution of display_alert() and update nameOfGlobalArray to match response.notification_array if the conditional returns true, like:
var notificationsArray = [];
setInterval(function(){
$.get(generate_site_url() + 'user.php?action=get_notifications', function(data) {
response = $.parseJSON(data);
if ('error' in response)
{
return;
}
if (response.notification_array.length == 0)
{
return;
}
$('.user-notification').text(response.notification_count);
$('.no-notes').hide();
var notificationStr = '';
for (var key in response.notification_array)
{
var notification = response.notification_array[key];
var notificationHTML = '<li' + ((notification.notification_seen == false) ? ' style="background: #fffaf1;"' : '') + '>';
notificationHTML += '<a href="' + notification.notification_target + '" id="nid-' + notification.notification_id + '">';
notificationHTML += '<span class="glyphicon glyphicon-' + ((notification.notification_type == 'like') ? 'thumbs-up' : (notification.notification_type == 'dislike') ? 'thumbs-down' : (notification.notification_type == 'favorite') ? 'heart' : 'bell') + '"></span> ';
notificationHTML += notification.notification_message;
notificationHTML += '</a></li>';
notificationStr += notification.notification_message + '<br />';
$('.notifications-dropdown').prepend($(notificationHTML));
}
if(response.notification_array.length > notificationsArray.length)
{
display_alert(notificationStr, 'danger', 5000, 'bottom');
notificationsArray = response.notification_array;
}
});
}, 10000);
[EDIT] BotskoNet's method uses less data, and apparently my brain wasn't turned on :P Both will work, though.
Does user.php mark a notification as seen once it has been delivered? I will assume not, but if so you just need to check if new notifications came in and only call the display_alert() if so.
Keeping track of notification count or comparing string is not enough. There are plenty of use cases where this will result in false positives. But I see there is a notification_id field:
var delivered= [];
setInterval(function(){
// ajax stuff
for (var key in response.notification_array){
var notification = response.notification_array[key];
// check if the notification has been delivered
if ($.inArray(notification.notification_id, delivered) === -1){
// notification has not been delivered
delivered.push(notification.notification_id);
// process notification as normal
}
}
// only display the alert if there is something to display...
if (notificationStr.length > 0)
display_alert(...);
}, 10000);

JS Removing Labels Font Style - MVC3

I have a label which displays the number of characters used in a textbox. When the page first loads it looks fine as it is small and in italics. I am using Bootstrap for that styling.
<label id="lblCharactersRemaining"><small><em>0 Out Of 255 Characters</em></small></label>
My JavaScript checks and updates the text in this label with the number of characters a user enters, this also works fine.
The problem is that each time the JS activates the styling goes back to the default MVC type. How can I make sure that when the JS executes that it doesn't remove the Bootstrap styling?
My JS is:
<script type="text/javascript">
var maximumLength = '#System.Configuration.ConfigurationManager.AppSettings["MaximumTextBoxLength"]';
if (document.getElementById("ObjectTextBox")) {
var txtbox = document.getElementById("ObjectTextBox");
txtbox.onkeyup = function () { IsMaxLength(this); };
}
function IsMaxLength(objTxtCtrl) {
if (objTxtCtrl.getAttribute && objTxtCtrl.value.length > maximumLength) {
objTxtCtrl.value = objTxtCtrl.value.substring(0, maximumLength);
}
if (document.all) {
document.getElementById('lblCharactersRemaining').innerText = (objTxtCtrl.value.length) + ' Out Of ' + maximumLength + ' Characters';
}
else {
document.getElementById('lblCharactersRemaining').textContent = (objTxtCtrl.value.length) + ' Out Of ' + maximumLength + ' Characters';
}
if (objTxtCtrl.value.length == 0) {
document.getElementById('lblCharactersRemaining').textContent = '0 Out Of ' + maximumLength;
}
}
</script>
Try :
function IsMaxLength(objTxtCtrl) {
if (objTxtCtrl.getAttribute && objTxtCtrl.value.length > maximumLength) {
objTxtCtrl.value = objTxtCtrl.value.substring(0, maximumLength);
}
if (document.all) {
$('#lblCharactersRemaining').html('<small><em>' + objTxtCtrl.value.length + ' Out Of ' + maximumLength + ' Characters</em></small>');
}
else {
$('#lblCharactersRemaining').html('<small><em>' + objTxtCtrl.value.length + ' Out Of ' + maximumLength + ' Characters</em></small>');
}
if (objTxtCtrl.value.length == 0) {
$('#lblCharactersRemaining').html('<small><em>0 Out Of ' + maximumLength + '</em></small>');
}
}
Every time you launch the function, it deleted the tags 'small' and 'em', so just add them...
UPDATE : PS : Using Jquery language...
UPDATE AFTER COMMENT :
BOOTPLY : http://bootply.com/106485
CODE :
JS :
$('button.jquery').on('click', function(){
$('#lblCharactersRemaining').html('<small><em>0 Out Of 85200</em></small>');
});
$('button.nojquery').on('click', function(){
document.getElementById('lblCharactersRemaining').innerHTML = '<small><em>0 Out Of 666</em></small>';
});
HTML :
<label id="lblCharactersRemaining"><small><em>0 Out Of 255 Characters</em></small></label>
<button class="jquery">Change label with jquery</button>
<button class="nojquery">Change label without jquery syntax</button>

pagination with AJAX url

Im beginner in AJAX & JS so please bear with me.
I use this AJAX for the pagination :
$(function () {
var keyword = window.localStorage.getItem("keyword");
//pagination
var limit = 3;
var page = 0;
var offset = 0;
$("#btnLoad").on('click', function () {
page++;
if (page != 0)
offset = (page - 1) * limit;
$.ajax({
url: "http://localhost/jwmws/index.php/jwm/search/msmall/" + keyword + "/" + limit + "/" + offset, //This is the current doc
type: "GET",
error: function (jq, st, err) {
alert(st + " : " + err);
},
success: function (result) {
alert("offset=" + offset + " page =" + page);
//generate search result
$('#search').append('<p style="float:left;">Search for : ' + keyword + '</p>' + '<br/>' + '<p>Found ' + result.length + ' results</p>');
if (result.length == 0) {
//temp
alert("not found");
} else {
for (var i = 0; i < result.length; i++) {
//generate <li>
$('#list').append('<li class="box"><img class="picture" src="images/HotPromo/tagPhoto1.png"/><p class="name"><b>Name</b></p><p class="address">Address</p><p class="hidden"></p></li>');
}
var i = 0;
$(".box").each(function () {
var name, address, picture, id = "";
if (i < result.length) {
name = result[i].name;
address = result[i].address;
picture = result[i].boxpicture;
id = result[i].mallid;
}
$(this).find(".name").html(name);
$(this).find(".address").html(address);
$(this).find(".picture").attr("src", picture);
$(this).find(".hidden").html(id);
i++;
});
$(".box").click(function () {
//alert($('.hidden', this).html());
window.localStorage.setItem("id", $('.hidden', this).html());
$("#pagePort").load("pages/MallDetail.html", function () {});
});
}
}
});
}).trigger('click');
});
Please notice that i use the variables for pagination in the url:. I tried to alert the page and offset variable, and its working fine.
However, the AJAX only working for the first page (when page load). The rest is not working even though the page and offset variable's value is true.
Theres no warning/error in console. The data just not shown.
Any help is appreciated, Thanks :D
It is a bit hard to debug your code when the whole HTML is missing.
Could you put your code into JSFiddle, both HTML and JS.

Add <option> in IE 6 unwards

I've the code below written in JavaScript to add a new option to the select list from the opener window:
function updateSelectList()
{
var field = opener.document.objectdata.ticketPersonId;
if (true && opener && field)
{
var val = document.createElement('option');
var title = document.objectdata.titleId.options[document.objectdata.titleId.selectedIndex].text;
val.text = title + ' ' + document.objectdata.firstName.value + ' ' + document.objectdata.lastName.value + ':' + document.objectdata.username.value;
val.value = null;
val.selected = true;
field.add(val, null);
}
}
works all fine in Firefox, Google Chrome etc but not IE 6 :-(
please advise how I can make this work in IE 6 aswell.
Here's my snippet:
if (oldopt!=null || !horus.brokenDOM)
select.add(newopt, oldopt);
else
newopt=options[options.length]=new Option(newopt.text, newopt.value, false, false);
The definition of horus.brokenDOM is left to the reader :)
IIRC, I had some difficulty with using pre-defined Option objects (generally pulled out of another selectbox) in this context with IE, hence the in-place object creation.
function updateSelectList()
{
var field = opener.<%= updatelist %>;
if (<%= called %> && opener && field)
{
var val = opener.document.createElement('option');
var title = document.objectdata.titleId.options[document.objectdata.titleId.selectedIndex].text;
val.text = title + ' ' + document.objectdata.firstName.value + ' ' + document.objectdata.lastName.value + ':' + document.objectdata.username.value;
val.value = <%= thePerson != null ? thePerson.getId() : null %>;
val.selected = true;
try
{
field.add(val, null);
}
catch(error)
{
field.add(val, 0);
}
}
}
this seams to work. What a mission!

Categories