jQuery: changing each <p> in each <div> depending on if/else result - javascript

In my HTML I have a gallery in which each gallery item has the following format:
<div class="gallery-img">
<a href="#" target="_blank">
<img src="#" />
</a>
<p class="imgDescription">November 20th</p>
<span class="hidden">20141120</span>
</div>
I'm currently attempting to build a function which will allocate a differing string to each .imgDescription depending on what the difference is between the hidden <span> and an external today variable which holds the current date. Here's the JS/jQuery:
today = yyyy+mm+dd;
$('.gallery-img').each(function() {
var itemRelease = $('.gallery-img span');
var timeToRelease = itemRelease - today;
if(timeToRelease < -1) {
$('.imgDescription').val(timeToRelease + " " + "days ago.");
} else if(timeToRelease > +1) {
$(this).val("In" + " " + timeToRelease + " " + "days");
} else if(timeToRelease === -1) {
$(this).val("Released yesterday");
} else if(timeToRelease === 1) {
$(this).val("Releases tomorrow");
} else if(timeToRelease === 0) {
$(this).val("Releases today!");
}
});
How would I go about in getting jQuery to compare each <div>'s <span> value and then inserting the resulting case into the respective .imgDescription?
The contents of the today variable are defined earlier in the code.
I used if/else rather than a switch, as a previous thread indicated a switch would be 30x slower.
Completely stuck on this! Help would be greatly appreciated :)

You should compare each of .gallery-img
// wrap in document ready
$(function() {
var today = new Date();
var dd = today.getDate();
var mm = (today.getMonth()+1) * 100; //January is 0! *100 to form single number
var yyyy = today.getFullYear() * 10000; // *10000 to form single number
today = yyyy+mm+dd;
var todayString = today.toString();
$('.gallery-img').each(function() {
var $this = $(this);
var itemRelease = $this.find('span');
var imgDescription = $this.find('.imgDescription');
var timeToRelease = campareDate(toDate(todayString), toDate(itemRelease.text()));
console.log(timeToRelease);
if(timeToRelease > 1) {
imgDescription.text(timeToRelease + " " + "days ago.");
} else if(timeToRelease < -1) {
imgDescription.text("In" + " " + -timeToRelease + " " + "days");
} else if(timeToRelease === 1) {
imgDescription.text("Released yesterday");
} else if(timeToRelease === -1) {
imgDescription.text("Releases tomorrow");
} else if(timeToRelease === 0) {
imgDescription.text("Releases today!");
}
});
});
function toDate(str) {
return new Date(str.substr(0,4) + '-' + str.substr(4, 2) + '-' + str.substr(6, 2));
}
function campareDate(date1, date2) {
return Math.floor((date1 - date2) / (86400 * 1000));
}
Demo:
http://jsfiddle.net/70nzrgxy/1/

Your code is a bit of a mess. So i fixed a few bugs here and there.
<div class="gallery-img">
<a href="#" target="_blank">
<img src="#" />
</a>
<p class="imgDescription" release-date="2014-11-20">November 20th</p>
</div>
Removed span, i guess You don't need this since is hidden.
$('.gallery-img').each(function() {
var itemRelease = $(this).find('p').attr('release-date');
var itemReleaseDate = new Date(itemRelease);
var timeToRelease = dateDiff(today,itemReleaseDate);
if(timeToRelease < -1) {
$(this).find('p').text(timeToRelease + " " + "days ago.");
} else if(timeToRelease > 1) {
$(this).find('p').text("In" + " " + timeToRelease + " " + "days");
} else if(timeToRelease === -1) {
$(this).find('p').text("Released yesterday");
} else if(timeToRelease === 1) {
$(this).find('p').text("Releases tomorrow");
} else if(timeToRelease === 0) {
$(this).find('p').text("Releases today!");
}
});
Added a timediff function. If you have a questions, go ahead and ask.
http://jsfiddle.net/b3rfe4ty/

You want to output your strings to your .imgDescription?
$('.gallery-img').each(function() {
// do what you need...
$(this).find('.imgDescription').html("Description you want");
}

Related

Javascript- How to reset button counter when timer reaches 0

I'm trying to get a simple click counter function to countdown the number of clicks users are left to use, where the number of clicks left will reset every 24 hours.
I've look through a few tutorials and implemented it visually in the alert once user has maxed the click. But how do I get about only resetting the count once the timer reaches 0.
HTML
<p><button onclick="clickCounter()" type="button">Click</button></p>
<div id="result"></div>
JavaScript
function clickCounter() {
var d = new Date();
var hours = 24 - d.getHours();
var min = 60 - d.getMinutes();
if((min + '').length == 1){
min = '0' + min;
}
var sec = 60 - d.getSeconds();
if((sec + '').length == 1){
sec = '0' + sec;
}
if(typeof(Storage) !== "undefined") {
if (localStorage.clickcount) {
if(Number(localStorage.clickcount) <= 0){
alert('You have max the number of connect \nTime left: '+ hours+':'+min+':'+sec);
localStorage.clickcount =4;
}
localStorage.clickcount = Number(localStorage.clickcount)-1
}
else
{
localStorage.clickcount = 4;
}
document.getElementById("result").innerHTML = "You have " + localStorage.clickcount + " clicks left.";
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
}
}
Here's a sample of how it's running. Currently I've set it to reset right after the alert pops out, and I'm just figuring how to reset automatically when the timer is up. Thanks for any feedback and help
sample link
You can set an interval function to check the time and reset values when time is up. I've changed your code to add a interval function
checkClickCount();
function clickCounter() {
var d = new Date();
var hours = 24 - d.getHours();
var min = 60 - d.getMinutes();
if ((min + '').length == 1) {
min = '0' + min;
}
var sec = 60 - d.getSeconds();
if ((sec + '').length == 1) {
sec = '0' + sec;
}
if (typeof(Storage) !== "undefined") {
if (localStorage.clickcount) {
if (Number(localStorage.clickcount) < 1) {
alert('You have max the number of connect \nTime left: ' + hours + ':' + min + ':' + sec);
return;
}
localStorage.clickcount = Number(localStorage.clickcount) - 1
} else {
localStorage.clickcount = 4;
}
document.getElementById("result").innerHTML = "You have " + localStorage.clickcount + " clicks left.";
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
}
}
var intv = null;
function checkClickCount(){
// interval run a function in a specified period of time
intv = window.setInterval(function(){
var currentTime = new Date();
var remainDateTime = new Date();
remainDateTime.setHours(24 - currentTime.getHours());
remainDateTime.setMinutes(60 - currentTime.getMinutes());
remainDateTime.setSeconds(60 - currentTime.getSeconds());
if(localStorage.clickcount > 1){
return;
}
// If the remaining times finished, the click count will be reset
if(remainDateTime.getHours() + remainDateTime.getMinutes() + remainDateTime.getSeconds() == 0){
localStorage.clickcount = 4;
document.getElementById("result").innerHTML = "You have " + localStorage.clickcount + " clicks";
return;
}
document.getElementById("result").innerHTML = "You will get 4 more clicks in " + remainDateTime.getHours() + ":" + remainDateTime.getMinutes() + ":" + remainDateTime.getSeconds() + " later.";
}, 1000);
}

Ignore Sundays from jQuery date range picker

I'm using the following jQuery date range picker library : http://longbill.github.io/jquery-date-range-picker/
I would like to remove / hide all Sundays from all date range pickers while keeping a normal behavior on the date range pickers.
I tried to do something with beforeShowDay option :
beforeShowDay: function(t) {
var valid = t.getDay() !== 0; //disable sunday
var _class = '';
// var _tooltip = valid ? '' : 'weekends are disabled';
return [valid, _class];
}
but it only "disables" all Sundays whereas I want to remove / hide them:
Here's the fiddle I'm working on : https://jsfiddle.net/maximelafarie/dnbd01do/11/
EDIT:
Updated fiddle with #Swanand code: https://jsfiddle.net/maximelafarie/dnbd01do/18/
You could do it with just a little CSS but it does leave a gap:
.week-name th:nth-child(7),
.month1 tbody tr td:nth-child(7) {
display: none;
}
Hope this helps a little.
You need do changes in two functions in your daterangepicker.js file:
createMonthHTML()
function createMonthHTML(d) { var days = [];
d.setDate(1);
var lastMonth = new Date(d.getTime() - 86400000);
var now = new Date();
var dayOfWeek = d.getDay();
if ((dayOfWeek === 0) && (opt.startOfWeek === 'monday')) {
// add one week
dayOfWeek = 7;
}
var today, valid;
if (dayOfWeek > 0) {
for (var i = dayOfWeek; i > 0; i--) {
var day = new Date(d.getTime() - 86400000 * i);
valid = isValidTime(day.getTime());
if (opt.startDate && compare_day(day, opt.startDate) < 0) valid = false;
if (opt.endDate && compare_day(day, opt.endDate) > 0) valid = false;
days.push({
date: day,
type: 'lastMonth',
day: day.getDate(),
time: day.getTime(),
valid: valid
});
}
}
var toMonth = d.getMonth();
for (var i = 0; i < 40; i++) {
today = moment(d).add(i, 'days').toDate();
valid = isValidTime(today.getTime());
if (opt.startDate && compare_day(today, opt.startDate) < 0) valid = false;
if (opt.endDate && compare_day(today, opt.endDate) > 0) valid = false;
days.push({
date: today,
type: today.getMonth() == toMonth ? 'toMonth' : 'nextMonth',
day: today.getDate(),
time: today.getTime(),
valid: valid
});
}
var html = [];
for (var week = 0; week < 6; week++) {
if (days[week * 7].type == 'nextMonth') break;
html.push('<tr>');
for (var day = 0; day < 7; day++) {
var _day = (opt.startOfWeek == 'monday') ? day + 1 : day;
today = days[week * 7 + _day];
var highlightToday = moment(today.time).format('L') == moment(now).format('L');
today.extraClass = '';
today.tooltip = '';
if (today.valid && opt.beforeShowDay && typeof opt.beforeShowDay == 'function') {
var _r = opt.beforeShowDay(moment(today.time).toDate());
today.valid = _r[0];
today.extraClass = _r[1] || '';
today.tooltip = _r[2] || '';
if (today.tooltip !== '') today.extraClass += ' has-tooltip ';
}
var todayDivAttr = {
time: today.time,
'data-tooltip': today.tooltip,
'class': 'day ' + today.type + ' ' + today.extraClass + ' ' + (today.valid ? 'valid' : 'invalid') + ' ' + (highlightToday ? 'real-today' : '')
};
if (day === 0 && opt.showWeekNumbers) {
html.push('<td><div class="week-number" data-start-time="' + today.time + '">' + opt.getWeekNumber(today.date) + '</div></td>');
}
if(day == 0){
html.push('<td class="hideSunday"' + attributesCallbacks({}, opt.dayTdAttrs, today) + '><div ' + attributesCallbacks(todayDivAttr, opt.dayDivAttrs, today) + '>' + showDayHTML(today.time, today.day) + '</div></td>');
}else{
html.push('<td ' + attributesCallbacks({}, opt.dayTdAttrs, today) + '><div ' + attributesCallbacks(todayDivAttr, opt.dayDivAttrs, today) + '>' + showDayHTML(today.time, today.day) + '</div></td>');
}
}
html.push('</tr>');
}
return html.join('');
}
In this function i have added class hideSunday while pushing the element.
The 2nd function is getWeekHead():
function getWeekHead() {
var prepend = opt.showWeekNumbers ? '<th>' + translate('week-number') + '</th>' : '';
if (opt.startOfWeek == 'monday') {
return prepend + '<th>' + translate('week-1') + '</th>' +
'<th>' + translate('week-2') + '</th>' +
'<th>' + translate('week-3') + '</th>' +
'<th>' + translate('week-4') + '</th>' +
'<th>' + translate('week-5') + '</th>' +
'<th>' + translate('week-6') + '</th>' +
'<th class="hideSunday">' + translate('week-7') + '</th>';
} else {
return prepend + '<th class="hideSunday">' + translate('week-7') + '</th>' +
'<th>' + translate('week-1') + '</th>' +
'<th>' + translate('week-2') + '</th>' +
'<th>' + translate('week-3') + '</th>' +
'<th>' + translate('week-4') + '</th>' +
'<th>' + translate('week-5') + '</th>' +
'<th>' + translate('week-6') + '</th>';
}
}
In this file, I have added class to week-7 header.
CSS:
.hideSunday{display:none;}
Please note, I have not checked all the scenario but it will do trick for you.
I finally ended up by letting the Sundays appear (but completely disabling them).
These questions inspired me :
Moment.js - Get all mondays between a date range
Moment.js: Date between dates
So I created a function as follows which returns an array that contains the "sundays" (or whatever day you provide as dayNumber parameter) in the date range you selected:
function getDayInRange(dayNumber, startDate, endDate, inclusiveNextDay) {
var start = moment(startDate),
end = moment(endDate),
arr = [];
// Get "next" given day where 1 is monday and 7 is sunday
let tmp = start.clone().day(dayNumber);
if (!!inclusiveNextDay && tmp.isAfter(start, 'd')) {
arr.push(tmp.format('YYYY-MM-DD'));
}
while (tmp.isBefore(end)) {
tmp.add(7, 'days');
arr.push(tmp.format('YYYY-MM-DD'));
}
// If last day matches the given dayNumber, add it.
if (end.isoWeekday() === dayNumber) {
arr.push(end.format('YYYY-MM-DD'));
}
return arr;
}
Then I call this function in my code like that:
$('#daterange-2')
.dateRangePicker(configObject2)
.bind('datepicker-change', function(event, obj) {
var sundays = getDayInRange(7, moment(obj.date1), moment(obj.date1).add(selectedDatesCount, 'd'));
console.log(sundays);
$('#daterange-2')
.data('dateRangePicker')
.setDateRange(obj.value, moment(obj.date1)
.add(selectedDatesCount + sundays.length, 'd')
.format('YYYY-MM-DD'), true);
});
This way, I retrieve the amount of sundays in the date range I selected. For example, if there's two sundays in my selection (with sundays.length), I know I have to set two additional workdays to the user selection (in the second date range picker).
Here's the working result:
With the above screenshot, you can see the user selected 4 workdays (5 with sunday but we don't count it). Then he click on the second calendar and the 4 workdays automatically apply.
Here's the result if the period apply over a sunday (we add one supplementary day and Xfor X sundays in the period):
Finally, here's the working fiddle: https://jsfiddle.net/maximelafarie/dnbd01do/21/
I want to thank any person that helped me. The question was hard to explain and to understand.
You can also do it by setting a custom css class and use it in beforeShowDay like below
.hideSunDay{
display:none;
}
beforeShowDay: function(t) {
var valid = t.getDay() !== 0; //disable sunday
var _class = t.getDay() !== 0 ? '' : 'hideSunDay';
// var _tooltip = valid ? '' : 'weekends are disabled';
return [valid, _class];
}
But it only hides the sundays beginning from current day.
Here is a working fiddle
https://jsfiddle.net/dnbd01do/16/

JS AM/PM times always show AM

I am making a simple time calculator in javascript. I have converted the times into 12-hour instead of 24 hour time for simplicity, however the code I have for calculating am/pm always shows am. Any reason why this would be happening?
Here is my code:
function solveTime(x) {
var suffixSolve = (utcHours + x) % 24;
var suffix = "am";
if (utcHours > 12) {
var suffix = "pm";
}
if (utcMinutes == 0) {
utcMinutesLead = "00";
}
if (utcMinutes < 10) {
utcMinutesLead = "0" + utcMinutes;
}
var timeSolve = (((utcHours + x) + 11) % 12 + 1);
var timeTotal = timeSolve + ":" + utcMinutesLead + " " + suffix;
var utcMod = x;
if (utcMod > 0) {
utcMod = "+" + utcMod;
}
document.getElementById(x).innerHTML = "(UTC" + utcMod + ") " + timeTotal;
}
and here is the code behind utcHours
var masterTimeUTC = new Date();
var utcHours = masterTimeUTC.getUTCHours();
var utcMinutes = masterTimeUTC.getUTCMinutes();
var utcSeconds = masterTimeUTC.getUTCSeconds();
var utcMinutesLead = masterTimeUTC.getUTCMinutes();
Example here: http://codepen.io/markgamb/pen/gwGkbo
The issue is you should be checking whether suffixSolve is greater than 12 instead of utcHours, because utcHours does not change due to the value of x. Since you can shift the hours forward and backwards, I created a variable shift to handle that.
function solveTime(x) {
if (x < 0) {
var shift = 24 + x;
} else {
var shift = x;
}
var suffixSolve = (utcHours + shift) % 24;
var suffix = "am";
if (suffixSolve > 12) {
suffix = "pm";
}
if (utcMinutes == 0) {
utcMinutesLead = "00";
}
if (utcMinutes < 10) {
utcMinutesLead = "0" + utcMinutes;
}
var timeSolve = (((utcHours + x) + 11) % 12 + 1);
var timeTotal = timeSolve + ":" + utcMinutesLead + " " + suffix;
var utcMod = x;
if (utcMod > 0) {
utcMod = "+" + utcMod;
}
document.getElementById(x).innerHTML = "(UTC" + utcMod + ") " + timeTotal;
}
var masterTimeUTC = new Date();
var utcHours = masterTimeUTC.getUTCHours();
var utcMinutes = masterTimeUTC.getUTCMinutes();
var utcSeconds = masterTimeUTC.getUTCSeconds();
var utcMinutesLead = masterTimeUTC.getUTCMinutes();
solveTime(4);
solveTime(0);
solveTime(-8);
<div id="4"></div>
<div id="-8"></div>
<div id="0"></div>

Increment/Decrement date in datepicker on mousewheel up/down respectively

I have a datepicker. I want to increment the date by 1 day as mouse wheel up is fired and decrement the date by 1 day as mouse wheel down is fired (upto the minimum possible date).
Below is my code snippet:
HTML
<input type="text" id="txtFromDate" class="calender"/>
JS
$(document).ready(function(){
$("#txtFromDate").datepicker({
minDate: new Date()
});
$("#txtFromDate").datepicker("setDate", new Date()); });
$('.calender').bind('mousewheel DOMMouseScroll', function (event) {
$id = $(this).attr('id');
$minDate = $('#' + $id).datepicker("option", "minDate");
$minDate = ($minDate.getMonth() + 1) + "/" + $minDate.getDate() + "/" + $minDate.getFullYear();
$datePickerDate = $('#' + $id).datepicker("getDate");
$datePickerDate = ($datePickerDate.getMonth() + 1) + "/" + $datePickerDate.getDate() + "/" + $datePickerDate.getFullYear();
var days = parseInt("1", 10);
if (event.originalEvent.wheelDelta > 0 || event.originalEvent.detail < 0) {
$datePickerDate = new Date($datePickerDate);
$datePickerDate = $datePickerDate.setDate($datePickerDate.getDate() + days);
}
else {
if ($datePickerDate >= $minDate && $('#' + $id ).val() != "") {
$datePickerDate = new Date($datePickerDate);
$datePickerDate = $datePickerDate.setDate($datePickerDate.getDate() - days);
}
}
alert($datePickerDate);
$('#' + $id).val($datePickerDate);
$('#' + $id).datepicker("setDate", $datePickerDate);
});
But the $datePickerDate value is coming to be as 1464028200000.
Here is the Non-Working Demo
What am I doing wrong?

Jquery mobile input in collapsilble problem

I have a list of collapsible times like in screen shot.. and a droplist.. in drop list you can choose the time how collapsible will separate times.. When i open activity first time...it's working fine but when i choose another time in droplist and he update collapsibles input loses their style and not working..
here is droplist change event->>
$('#timeDropList').change(function() {
$('div.addedEntry').remove();
drawTemplate();
});
and here is draw collapsibles function->>
function drawTemplate() {
var selectedValue = parseInt($('#timeDropList').val());
var textProjectName = '<input type="text" class="projectName" value="" />';
var textProjectData = '<input style="height:50px;" type="text" class="projectEntry" value="" />';
var timespan;
if ($('.div-cell').hasClass('tapped')) {
var calToScheDate = $('.div-cell.tapped').find('.dayNumberCellValue')
.attr('data-a');
var calToScheMonth;
var calToScheDay;
if (calToScheDay = calToScheDate.substring(6, 8) < 10) {
calToScheDay = calToScheDate.substring(7, 8);
} else {
calToScheDay = calToScheDate.substring(6, 8);
}
if (calToScheMonth = calToScheDate.substring(4, 6) < 10) {
calToScheMonth = calToScheDate.substring(5, 6);
} else {
calToScheMonth = calToScheDate.substring(4, 6);
}
timespan = new Date(calToScheDate.substring(0, 4), calToScheMonth,
calToScheDay, 9, 0);
} else {
timespan = new Date();
timespan = new Date(timespan.getFullYear(), timespan.getMonth(),
timespan.getDate(), 9, 0);
}
while (timespan.getHours() < 18 || timespan.getHours() == 18
&& timespan.getMinutes() == 0) {
var hoursFrom = timespan.getHours();
var minsFrom = timespan.getMinutes();
if (minsFrom < 10) {
minsFrom = "0" + minsFrom;
}
if (hoursFrom < 10) {
hoursFrom = "0" + hoursFrom;
}
var hoursTo = timespan.getHours();
var minsTo = timespan.getMinutes() + selectedValue
if (minsTo == 60) {
minsTo = "00";
hoursTo++;
} else if (minsTo < 10) {
minsTo = "0" + minsTo;
}
var collDiv = '<div class="addedEntry" data-theme="c" data-role="collapsible" id='+hoursFrom+minsFrom+hoursTo+minsTo+' data-collapsed="true"><h3 class="results-header">'
+ hoursFrom
+ ":"
+ minsFrom
+ " - "
+ hoursTo
+ ":"
+ minsTo +'</h3>' + '</div>';
$('.spanTimetable').append(collDiv);
timespan.setMinutes(timespan.getMinutes() + selectedValue);
}
$('.addedEntry').append(textProjectName);
$('.addedEntry').append(textProjectData);
$('.results-header').append('<img class="checkOrCross" />');
$('#timetable .addedEntry').collapsible({
refresh : true
});
}
You will need to refresh the jQM using .page()
Maybe try:
$('#timeDropList').change(function() {
$('div.addedEntry').remove();
drawTemplate();
});
$('#name of your page').page();

Categories