I have been trying to make recurring events in fullcalendar, I really find dow feature helpful, but I really want to add date ranges to it.
In other words, dow : [1] will repeat a task for every single Monday, the problems is, I want to make it visible only in a date range I set.
You can not set ranges by using dow, you have to perform some custom functionality.
Lets suppose that you have fetched events data from your database which contains multiple event objects. each event object has start date end date property and also to and from properties which contains date range , isRecurring is a Boolean property which we will add true in case of recurring events otherwise it will be false.
Remember the recurring events take start and end time without date, you only need to give them time slots, like start = "16:00" and end = "20:00" You can extract time by using moment js like i did while initializing my event object
{
title:'Recurring Event',
start: moment.utc(event.start).format('HH:mm'),
end: moment.utc(event.end).format('HH:mm'),
isRecurrring: event.isRecurring,
ranges: [{
start: moment(event.from),
end: moment(event.to),
}],
}
I have used moment.utc() to ignore the timezone.
Now override the eventRender function while initializing your fullCalendar. Your eventRender function will be
eventRender: function(event, element, view){
if (event.isRecurrring) {
return (event.ranges.filter(function(range){
return (moment(event.start).isBefore(range.end) &&
moment(event.end).isAfter(range.start));
}).length) > 0;
}
}
You coulded set ranges as this example:
repeatingEvents.push({
title: "From: " + inputDateStart + " To: " + inputDateFinish,
start: vm.timeStart,
end: vm.timeFinish,
dow: listDay,
ranges: [{
start: dateStart,
end: dateFinish
}]
})
$("#calendar").fullCalendar("refetchEvents");
So you can use both "dow" and "ranges". Hope help for you!
function createCalendar() {
vm.uiConfig = timeProfileFactory.getCalendarConfig();
vm.uiConfig.calendar.eventClick = eventClick;
vm.uiConfig.calendar.eventDrop = alertOnDrop;
vm.uiConfig.calendar.eventResize = alertOnResize;
vm.uiConfig.calendar.eventRender = eventRender;
vm.uiConfig.calendar.select = selectSlot;
vm.uiConfig.calendar.header.center = "title";
vm.events = function(start, end, timezone, callback) {
callback(repeatingEvents);
}
vm.eventSources = [vm.events];
};
function selectSlot(start, end, jsEvent, view) {
var allDay = !start.hasTime() && !end.hasTime();
var offset = ((new Date()).getTimezoneOffset())/60;
var dateStart = (new Date(start)).setHours(0, 0, 0, 0);
dateStart = new Date(dateStart);
dateStart.setHours(dateStart.getHours() - offset);
dateStart = dateStart.toISOString();
var timeStart = (new Date(start)).toISOString();
var timeEnd = (new Date(end)).toISOString();
timeStart = timeStart.split('T')[0];
timeEnd = timeEnd.split('T')[0];
var length = repeatingEvents.length;
if(positionEvent == -1 || repeatingEvents.length == 0) {
positionEvent = 0;
} else {
positionEvent = repeatingEvents[length - 1].position + 1;
}
repeatingEvents.push({
title: "From: " + start.format("DD/MM/YYYY"),
start: start.format("HH:mm"),
end: end.format("HH:mm"),
dow: [new Date(start).getDay()],
ranges: [{
start: dateStart,
end: null
}],
position: positionEvent,
allDay: false
});
length++;
if(repeatingEvents[length - 1].end == "00:00") {
repeatingEvents[length - 1].end = "24:00";
}
if(allDay) {
repeatingEvents[length - 1].allDay = true;
repeatingEvents[length - 1].start = null;
repeatingEvents[length - 1].end = null;
}
$("#calendar").fullCalendar("refetchEvents");
};
function eventClick(event, date, jsEvent, view) {
isOpenDialog = true;
for(var i = 0; i < repeatingEvents.length; i++) {
if(repeatingEvents[i].position == event.position && isOpenDialog) {
selectIndex = i;
vm.timeStart = repeatingEvents[i].start;
vm.timeFinish = repeatingEvents[i].end;
vm.dateStart = repeatingEvents[i].title.split(' ')[1];
if(repeatingEvents[i].ranges[0].end == null) {
vm.dateFinish = "";
vm.radioValue = "never";
} else {
vm.dateFinish = repeatingEvents[i].title.split(' ')[3];
vm.radioValue = "on";
}
angular.forEach(vm.checkDays, function(item) {
item.checked = false;
});
angular.forEach(event.dow, function(index) {
vm.checkDays[index].checked = true;
})
openDialog();
break;
}
}
};
function alertOnResize(event, delta, revertFunc, jsEvent, ui, view) {
for(var i in repeatingEvents) {
if(repeatingEvents[i].position == event.position) {
var timeFinish = event.end.format("HH:mm");
if(timeFinish == "00:00") {
timeFinish = "24:00";
}
repeatingEvents[i].end = timeFinish;
break;
}
}
$("#calendar").fullCalendar("refetchEvents");
};
function alertOnDrop(event, delta, revertFunc, jsEvent, ui, view) {
for(var i in repeatingEvents) {
if(repeatingEvents[i].position == event.position) {
if(repeatingEvents[i].allDay || event.allDay) {
revertFunc();
} else {
var timeStart = event.start.format("HH:mm");
var timeFinish = event.end.format("HH:mm");
var dateStart = repeatingEvents[i].ranges[0].start;
var dateFinish = repeatingEvents[i].ranges[0].end;
var oldTimeStart = repeatingEvents[i].start.split(':')[0]*3600 + repeatingEvents[i].start.split(':')[1]*60;
var newTimeStart = timeStart.split(':')[0]*3600 + timeStart.split(':')[1]*60;
var deltaHour = newTimeStart - oldTimeStart;
var deltaDay = (delta/1000 - deltaHour)/86400;
dateStart = new Date(dateStart);
dateStart.setDate(dateStart.getDate() + deltaDay);
dateStart = dateStart.toISOString();
var title;
if(dateFinish != null) {
dateFinish = new Date(dateFinish);
dateFinish.setDate(dateFinish.getDate() + deltaDay);
dateFinish = dateFinish.toISOString();
title = "From: " + moment(dateStart).format("DD/MM/YYYY") + " To: " + moment(dateFinish).format("DD/MM/YYYY");
} else {
title = "From: " + moment(dateStart).format("DD/MM/YYYY");
}
for(var j in event.dow) {
repeatingEvents[i].dow[j] = parseInt(repeatingEvents[i].dow[j]) + deltaDay;
if(repeatingEvents[i].dow[j] > 6) {
repeatingEvents[i].dow.splice(j, 1);
}
}
repeatingEvents[i].start = timeStart;
repeatingEvents[i].end = timeFinish;
repeatingEvents[i].ranges[0].start = dateStart;
repeatingEvents[i].ranges[0].end = dateFinish;
repeatingEvents[i].title = title;
if(timeFinish == "00:00") {
repeatingEvents[i].end = "24:00";
}
$("#calendar").fullCalendar("refetchEvents");
}
break;
}
}
};
function eventRender(event, element, view) {
var removeEvent = $("<i class='removeEvent icons8-delete pull-right'></i>");
removeEvent.on("click", function() {
isOpenDialog = false;
vm.removeEvent(event);
});
element.find(".fc-content").prepend(removeEvent);
var result;
if(event.ranges[0].end == null) {
result = (event.ranges.filter(function(range) {
var startConvert = (new Date(event.start)).toISOString();
return (event.start.isAfter(range.start) || startConvert == range.start);
}).length) > 0;
} else {
result = (event.ranges.filter(function(range) {
return (event.start.isBefore(range.end) && event.end.isAfter(range.start));
}).length) > 0;
}
return result;
};
Related
When we paste the content in trix-editor the href not getting paste as simple text. How can we make it as a link.
var TrixAutoLinker,
bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
addEventListener("trix-initialize", function(event) {
return new TrixAutoLinker(event.target);
});
TrixAutoLinker = (function() {
var INPUT, PATTERN, isValidURL;
function TrixAutoLinker(element) {
this.element = element;
this.autoLink = bind(this.autoLink, this);
this.editor = this.element.editor;
this.element.addEventListener("trix-render", this.autoLink);
this.autoLink();
}
TrixAutoLinker.prototype.autoLink = function() {
var currentRange, i, len, range, ref, ref1, results1, url;
ref = this.getURLsWithRanges();
results1 = [];
for (i = 0, len = ref.length; i < len; i++) {
ref1 = ref[i], url = ref1.url, range = ref1.range;
if (this.getHrefAtRange(range) !== url) {
currentRange = this.editor.getSelectedRange();
this.editor.setSelectedRange(range);
if (this.editor.canActivateAttribute("href")) {
this.editor.activateAttribute("href", url);
}
results1.push(this.editor.setSelectedRange(currentRange));
} else {
results1.push(void 0);
}
}
return results1;
};
TrixAutoLinker.prototype.getDocument = function() {
return this.editor.getDocument();
};
TrixAutoLinker.prototype.getDocumentString = function() {
return this.getDocument().toString();
};
TrixAutoLinker.prototype.getHrefAtRange = function(range) {
return this.getDocument().getCommonAttributesAtRange(range).href;
};
PATTERN = /(https?:\/\/\S+\.\S+)\s/ig;
TrixAutoLinker.prototype.getURLsWithRanges = function() {
var match, position, range, results, string, url;
results = [];
string = this.getDocumentString();
while (match = PATTERN.exec(string)) {
url = match[1];
if (isValidURL(url)) {
position = match.index;
range = [position, position + url.length];
results.push({
url: url,
range: range
});
}
}
return results;
};
INPUT = document.createElement("input");
INPUT.type = "url";
INPUT.required = true;
isValidURL = function(value) {
INPUT.value = value;
return INPUT.checkValidity();
};
return TrixAutoLinker;
})();
// ---
// generated by coffee-script 1.9.2
Is there a good way to handle the ProvisionedThroughputExceededException without increasing the Read/Write capacity of the table? Ideally, I would like to decrease the throughput on the scripting side such that the exception won't be triggered.
function saveDataToDynamodb(data, scriptName){
let items = [];
var processItemsCallback = function (err, data) {
if (err) {
console.log(err);
setTimeout(() => {console.log('sleep for error')}, Math.floor(0.5 * 1000 + 1000));
}else {
if (Object.keys(data.UnprocessedItems).length > 0) {
//setTimeout(() => {console.log('sleep to wait')}, Math.floor(Math.random() * 1000 + 1000));
var params = {};
params.RequestItems = data.UnprocessedItems;
docClient.batchWrite(params, processItemsCallback);
}
}
};
data.forEach(station => {
let stationName = station.stationName
if (stationName == null) {
stationName = "null"
}
//console.log(station.stationId + "_" + stationName)
let pollutants = station.pollutants
let unique_set = new Set()
let aqiArr = [];
let sortedKey;
let timestamp;
pollutants.forEach(pollutant => {
timestamp = pollutant.utcMoment
sortedKey = station.stationId + "_" + timestamp + "_" + station.latitude + "_" + station.longitude + "_" + pollutant.pollutant;
if (!unique_set.has(sortedKey)) {
unique_set.add(sortedKey)
if (!scriptName.includes("Pollen")) { // calculate AQI if it's not pollen data
let polValue = processPollutant(pollutant.value, pollutant.pollutant);
let pollutantAQI;
if (pollutant.pollutant == "o3" && pollutant.avgInterval == "1h") {
pollutantAQI = aqiCalc.calcEpaAqi(polValue, pollutant.pollutant, true);
} else {
pollutantAQI = aqiCalc.calcEpaAqi(polValue, pollutant.pollutant, false);
}
//console.log("polValue: " + polValue + ", Pollutant value: " + pollutant.value + ", pollutant: " + pollutant.pollutant + ", AQI: " + pollutantAQI)
aqiArr.push(pollutantAQI);
}
items.push({
PutRequest: {
Item: {
"stationId": station.stationId,
"stationName": String(station.stationName),
"latitude": station.latitude,
"longitude": station.longitude,
"pollutant": pollutant.pollutant,
"avgInterval": pollutant.avgInterval,
"units": pollutant.units,
"initialUnits": pollutant.initialUnits,
"value": pollutant.value,
"sortedKey": sortedKey,
"timestamp": timestamp
}
}
});
if (items.length >= 24) {
let params = {
RequestItems: {
pollutantFullData: items
}
};
docClient.batchWrite(params, processItemsCallback);
items = []
}
}
});
if (aqiArr.length > 0) {
var finalAqi = getMaxAsInteger(aqiArr);
if (finalAqi > 500) {
finalAqi = 500;
}
items.push({
PutRequest: {
Item: {
"stationId": station.stationId,
"stationName": String(station.stationName),
"latitude": station.latitude,
"longitude": station.longitude,
"pollutant": "aqi",
"avgInterval": "1h",
"units": "ppb",
"initialUnits": "ppm",
"value": finalAqi,
"sortedKey": station.stationId + "_" + timestamp + "_" + station.latitude + "_" + station.longitude + "_aqi",
"timestamp": timestamp
}
}
});
}
if (items.length > 0) {
let params = {
RequestItems: {
pollutantFullData: items
}
};
docClient.batchWrite(params, processItemsCallback);
}
});
}
It seems as though the batchWrite operation is running asynchronously, such that the various threads are hitting the API endpoint at the same time, thus causing the error. How can the previous code be changed to resolve the error?
I have a Google Sheets file which calls Google Analytics and pulls metrics. This works great. What I want to do is pull metrics by channel so that the far left column is a collection of channels (PPC, Display, Organic, Social, Email, Referral, Affiliate, Direct). Do I need to use the Multi-Channel Funnel setup? Or is there a better way to do this?
function getGAData() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("test Data");
// var startDate = dateToYMD(sheet.getRange(3,3).getValue());
// var endDate = dateToYMD(sheet.getRange(3,4).getValue());
var dateRanges = readDateRanges(sheet);
var profileIds = readProfileIds(sheet);
var GAMetrics = readGAMetrics(sheet);
var results = [];
var metrics = [];
var optArgs = [];
var filterCount = 0;
var prevFilter = '**NONE**';
var i, j, k;
var profileResults;
var tempResults;
for (i = 0; i < GAMetrics[0].length; i++) {
// Utilities.sleep(100);
if (prevFilter != GAMetrics[1][i]) {
metrics[filterCount] = GAMetrics[0][i];
optArgs[filterCount] = {
'start-index': '1',
'max-results': '10' // Display the first 250 results.
};
if (GAMetrics[1][i] != '')
optArgs[filterCount].filters = GAMetrics[1][i];
if (GAMetrics[2][i] != '')
optArgs[filterCount].segment = GAMetrics[2][i];
filterCount++;
} else {
metrics[filterCount-1] = metrics[filterCount-1] + ',' + GAMetrics[0][i];
}
prevFilter = GAMetrics[1][i];
}
for (i = 0; i < profileIds.length; i++) { // get GA data for each of the rows of input
profileResults = [];
var tableId = 'ga:' + profileIds[i][0];
var startDate = dateToYMD(dateRanges[i][0]);
var endDate = dateToYMD(dateRanges[i][1]);
for (j = 0; j < metrics.length; j++) {
var metric = metrics[j];
var options = optArgs[j];
//var options = {
// 'dimensions': 'ga:source',
//};
try {
// Make a request to the API.
tempResults = Analytics.Data.Ga.get(
'ga:' + profileIds[i][0], // Table id (format ga:xxxxxx).
dateToYMD(dateRanges[i][0]), // Start-date (format yyyy-MM-dd).
dateToYMD(dateRanges[i][1]), // End-date (format yyyy-MM-dd).
metrics[j], // Comma seperated list of metrics.
optArgs[j]);
var report = Analytics.Data.Ga.get(tableId, startDate, endDate, metric,
options);
if (typeof tempResults.getRows() != 'undefined')
appendArray(profileResults, tempResults.getRows()[0]);
} catch (e) {
Logger.log(e + ' - Profile ID: ' + profileIds[i][0] + ' - Metrics: ' + metrics[j] );
}
}
//append Profile results to the set
for (k = profileResults.length; k < GAMetrics[0].length; k++)
profileResults[k] = '0';
results.push(profileResults);
// Utilities.sleep(200);
}
sheet.getRange(6, 13, results.length, GAMetrics[0].length).setValues(results); // populate results on spreadsheet
emailLog('don#test.com','startDate');
}
function readDateRanges(sheet){
var rowStart = 6;
var columnStart = 1;
var numRows = sheet.getLastRow() - rowStart + 1;
return sheet.getRange(rowStart, columnStart, numRows, 2).getValues();
}
function readProfileIds(sheet) {
var rowStart = 6;
var columnStart = 3;
var numRows = sheet.getLastRow() - rowStart + 1;
return sheet.getRange(rowStart, columnStart, numRows, 1).getValues();
}
function readGAMetrics(sheet) {
var rowStart = 2;
var columnStart = 13;
var numColumns = sheet.getLastColumn() - columnStart + 1;
return sheet.getRange(rowStart, columnStart, 3, numColumns).getValues();
}
function dateToYMD(date) {
var d = date.getDate();
var m = date.getMonth() + 1;
var y = date.getFullYear();
return '' + y + '-' + (m<=9 ? '0' + m : m) + '-' + (d <= 9 ? '0' + d : d);
}
function appendArray(a1,a2) {
var startSize = a1.length;
for (var i = 0; i < a2.length; i++)
a1[startSize + i] = a2[i];
}
function emailLog(emailAddress,reportDate) {
var recipient = emailAddress; // Session.getActiveUser().getEmail();
var subject = 'GA Data Pull - extract for ' + reportDate;
var body = Logger.getLog();
MailApp.sendEmail(recipient, subject, body);
}
and thank you once again for your expert support. I have a rather nice implementation of flot, that has one very unfortunate bug. The plot routine works in a loop, so it creates as many plots as there are data files, that pass muster, in the directory. If there is only one data file, then only one plot, the resulting flot plot works fine and the check boxes turn the lines on and off as expected. If I have more than one data file and hence more than one flot plot.. only the bottom one seems to work correctly, the remainder lock up after either one toggle or none.
Can someone give me an idea how to create the flot plots so they do not interfere? I have read elsewhere that the function name does not need to be different, but have not verified this, and I did change the labels, but this added additional weirdness.
Quite a long code.. but it gives you most of what I know...
The first section here actually builds the data sets for flot... then the rest creates the plot...
<script type='text/javascript'>//<![CDATA[
$(function(){
var results = [
<?php
$downsample = 5;
for($k=0;$k<2; $k++){
//$k =0 is Left, $k = 1 is right
if ($k==0){
$side = "L";
$offset = 1;
} elseif ($k==1) {
$side = "R";
$offset = 0;
}
for ($m = 1; $m <= count($trackdata)-1; $m++){
echo "\n{\n\"label\": \"".$m.$side."\",\n"; //echo "\n{\n\"label\": \"".$m." ".$side."\",\n";
echo "\"data\": [";
for ($n=1;$n<=count($PSD[$m*3-2]);$n=$n+$downsample){
$tmp = "[".$PSD[$m*3-2][$n].",".$PSD[$m*3-$offset][$n]."]";
echo $tmp;
if ($n > count($PSD[$m*3-2])-$downsample){
echo "]}";
} else {
echo ",";
}
}
if ($m <> count($trackdata)-1){
echo ",";
} else if ($k<1){
echo ",";
}
}
}
echo "];";
?>
var options = {
legend: {
show: true
},
series: {
points: {
show: false
},
lines: {
show: true
}
},
grid: {
hoverable: true
},
xaxis: {
},
yaxis: {
}
};
var i = 0;
var track = 0;
choiceContainer = $("#labeler<?php echo $i ?>");
var table = $('<table />');
var row = $('<tr/>');
var cell = $('<td width=\"100\"/>');
var temp = $(table);
$.each(results, function(key, val) {
track = track + 1;
val.color = i;
++i;
l = val.label;
if (track == 1){
temp.append(row);
row.append(cell);
cell.append('Left Channel');
} else if(track == <?php echo $tracks ?>){
row = $('<tr/>');
temp.append(row);
cell = $('<td width=\"100\">');
row.append(cell);
cell.append('Right Channel');
} //else if ((track == 7) or (track == 14) or (track == 21) or (track == 28) or (track == 35)){
//}
cell = $('<td width=\"60\"/>');
row.append(cell);
var bar = $('<div style=\"width:18px; white-space:nowrap; float:left\"><bar />');
cell.append(bar);
var inp = $('<input name="' + l + '" id="' + l + '" type="checkbox" checked="checked">');
cell.append(inp);
var bits = $('<label>', {
text: l,
'for': l
});
cell.append(bits);
choiceContainer.append(temp);
});
function plotAccordingToChoices() {
var data = [];
choiceContainer.find("input:checked").each(function() {
var key = this.name;
for (var i = 0; i < results.length; i++) {
if (results[i].label === key) {
data.push(results[i]);
return true;
}
}
});
$.plot($("#placeholder<?php echo $i ?>"), data, options);
}
var previousPoint = null;
$("#placeholder<?php echo $i ?>").bind("plothover", function(event, pos, item) {
$("#x").text(pos.x.toFixed(2));
$("#y").text(pos.y.toFixed(2));
if (item) {
if (previousPoint != item.datapoint) {
previousPoint = item.datapoint;
$("#tooltip").remove();
var x = item.datapoint[0].toFixed(2),
y = item.datapoint[1].toFixed(2);
showTooltip(item.pageX, item.pageY, item.series.label + " $" + y);
}
} else {
$("#tooltip").remove();
previousPoint = null;
}
});
function showTooltip(x, y, contents) {
$('<div id="tooltip">' + contents + '</div>').css({
position: 'absolute',
display: 'none',
top: y + 5,
left: x + 15,
border: '1px solid #fdd',
padding: '2px',
backgroundColor: '#fee',
opacity: 0.80
}).appendTo("body").fadeIn(200);
}
plotAccordingToChoices();
choiceContainer.find("input").change(plotAccordingToChoices);
$('.legendColorBox > div').each(function(i){
$(this).clone().prependTo(choiceContainer.find("bar").eq(i));
});
});//]]>
</script>
Okay.. so the dust settled and I did sort out my issue, along with cleaning up a few things. First of all, I created a function for the plot routine. This uncovered the issue I was having, where I was reusing the same variables for the divs into which the data was going, hence the mixed up results. By creating the function, and then driving the function with custom variables for each iteration, the plots operate independently as they should. – Mark
function flotplot(results, choiceContainer, plotholder, numtracks, legendcontainer){
// pass in results, choicecontainer, plotholder
// results = data
// choiceContainer = $("#labeler1");
// plotholder = $("#placeholder0");
var options = {
legend: {
show: true,
container: legendcontainer,
noColumns: 2,
sorted: false
},
series: {
points: {
show: false
},
lines: {
show: true
}
},
grid: {
hoverable: true
},
xaxes: [{
axisLabel: 'Frequency (Hz)',
}],
yaxes: [{
axisLabel: 'Power (dB)',
}],
crosshair: {
mode: "xy",
color: 001,
lineWidth: .5
}
};
var i = 0;
var track = 0;
var table = $('<table />');
var row = $('<tr/>');
var cell = $('<td width=\"100\"/>');
var temp = $(table);
$.each(results, function(key, val) {
track = track + 1;
val.color = i;
++i;
l = val.label;
if (track == 1){
temp.append(row);
row.append(cell);
cell.append('Left Channel');
} else if(track == numtracks){
row = $('<tr/>');
temp.append(row);
cell = $('<td width=\"100\">');
row.append(cell);
cell.append('Right Channel');
} //else if ((track == 7) or (track == 14) or (track == 21) or (track == 28) or (track == 35)){
//}
cell = $('<td width=\"70\"/>');
row.append(cell);
var bar = $('<div style=\"width:18px; white-space:nowrap; float:left\"><bar />');
cell.append(bar);
var inp = $('<input name="' + l + '" id="' + l + '" type="checkbox" checked="checked">');
cell.append(inp);
var bits = $('<label>', {
text: l,
'for': l
});
cell.append(bits);
choiceContainer.append(temp);
});
function plotAccordingToChoices() {
var data = [];
choiceContainer.find("input:checked").each(function() {
var key = this.name;
for (var i = 0; i < results.length; i++) {
if (results[i].label === key) {
data.push(results[i]);
return true;
}
}
});
$.plot(plotholder, data, options);
}
var previousPoint = null;
plotholder.bind("plothover", function(event, pos, item) {
$("#x").text(pos.x.toFixed(2));
$("#y").text(pos.y.toFixed(2));
if (item) {
if (previousPoint != item.datapoint) {
previousPoint = item.datapoint;
$("#tooltip").remove();
var x = item.datapoint[0].toFixed(2),
y = item.datapoint[1].toFixed(2);
showTooltip(item.pageX, item.pageY, item.series.label + " " + y + "dB");
}
} else {
$("#tooltip").remove();
previousPoint = null;
}
});
function showTooltip(x, y, contents) {
$('<div id="tooltip">' + contents + '</div>').css({
position: 'absolute',
display: 'none',
top: y + 5,
left: x + 15,
border: '1px solid #fdd',
padding: '2px',
backgroundColor: '#fee',
opacity: 0.80
}).appendTo("body").fadeIn(200);
}
plotAccordingToChoices();
choiceContainer.find("input").change(plotAccordingToChoices);
$('.legendColorBox > div').each(function(i){
$(this).clone().prependTo(choiceContainer.find("bar").eq(i));
});
};//]]>
Here is the structure into which it writes:
echo "<div id=\"placeholder".$i."\" class=\"loading\" style=\"width:600px;height:300px;display: inline; position: relative; float: left\"></div>";
echo "<div id=\"legendholder".$i."\" class=\"loading\" style=\"width:200px; height:300px; display: inline; position: relative; float: left\"></div>";
echo "<div id=\"picker1\" style=\"clear: both\"><p id=\"choices".$i."\">Show the following Tracks:</p></div>";
echo "<div id=\"labeler".$i."\"></div>";
This is my asp code, can be the same done in Javascript?
HttpCookie cookie = this.Request.Cookies["Votes"];
if (cookie != null)
if (cookie.Values.Get(id.ToString()) == "true") return true;
return false;
function readTheCookie(the_info)
{
// load the cookie into a variable and unescape it
var the_cookie = document.cookie;
var the_cookie = unescape(the_cookie);
// separate the values from the cookie name
var broken_cookie = the_cookie.split("some parameter"); // parameter depends on how the cookie is stored
var the_values = broken_cookie["some index"]; // index of the value that you want
}
These are all the parts of reading a cookie, you can use this snippet to achieve what you want.
document.cookie gives you access to the cookies in JavaScript. You will need to do some parsing to do what you want to do.
using this code
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
function GetSetCookie() {
var version = getCookie("version");
if (version != null && version != "") {
if (version == 'full') {
version = 'text';
}
else {
version = 'full';
}
}
else {
version = 'full';
}
setCookie("version", version, 365);
window.top.location.reload();
}
I have found this code in W3schools which works for me
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
}
function checkCookie() {
var user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
setCookie("username", user, 365);
}
}
}