Cordova/Phonegap calendar plugin iOS create event - javascript

I'm using Cordova/Phonegap plugin found here:
https://github.com/EddyVerbruggen/Calendar-PhoneGap-Plugin
My app is an RSS feed that had different events everyday, I would like to change the javascript code so that the user is able to add to calendar and the function reads the title date at least.
In my main.js the function is:
function Calendar_Add(){
// prep some variables
var startDate = new Date("March 18, 2014 13:00:00");
var endDate = new Date("March 18, 2014 14:30:00");
var title = "Event Added!";
var location = "Home";
var notes = "Some notes about this event.";
var success = function(message) { alert("Success: " + JSON.stringify(message)); };
var error = function(message) { alert("Error: " + message); };
// create
window.plugins.calendar.createEventWithCalendar(title,location,notes,startDate,endDate,success,error);
}
This is creating an event but again I am having trouble making the variables. This is my full javascript page of what I have tried:
//jQuery get target page
function IE_navigate(index) {
Bindex = index;
$.mobile.changePage('#eventPage', 'slidefade');
$.each(data, function(i,item){
if (i == Bindex) {
//Clear if page was previously populated
//Populate page
$('#page-title').html(item.title + "<br />");
$('#page-region').html(item.Region + "<br />");
$('#page-content').html(item.fullInfo + "<br />");
/*
startDate = new Date(item.Date);
endDate = new Date(item.Date);
title = item.title;
place = item.Region;
*/
$(this).ready(function(e) {
$('#page-content').on('click','a', function(e){
e.preventDefault();
currentPage = $(this).attr('href');
window.open(currentPage, '_system', 'location=yes')
});
});
// return false;
return false
}
});
};
var Aindex = "";
var Bindex = "";
var data = [];
$(function () { Load_Content() });
function Load_Content() {
$('#feed').empty();
data = [];
$.ajax({
type: 'GET',
url:'http://www.e-grid.net/BayAreaTech/wp-rss2.php?cat=1',
dataType: 'xml',
success: function (xml) {
$('#header-title').html("e-Grid Mobile");
$(xml).find("item:lt(60)").each(function () {
var dateText = $(this).find("Date").text().toString();
var eventDate = moment(dateText,"YYYY-MM-DD");
var title = $(this).find("title").text();
var region = dateText.substr(8).toUpperCase();
if (region == "SCV") { region = "Santa Clara Valley";}
if (region == "OEB") { region = "Oakland/East Bay";}
if (region == "SF") { region = "San Francisco";}
if (region == "ALL") { region = "All regions";}
var description = $(this).find("description").text();
var infoDisplay = description.substr(0, description.indexOf(",")+120) + "..."; //Parsed DATE from description
var fullDescription = $(this).find('encoded').text();
var category = $(this).find("category").text();
var linkUrl = $(this).find("link").text();
var displayTitle = title;
var item = {title: displayTitle,
link: linkUrl,
infoDescription: infoDisplay,
Date: new Date(eventDate),
Region: region,
fullInfo: fullDescription,}
var now = moment().subtract('days', 1);
if (item.Date >= now){ data.push(item); }
});
data.sort(function (a, b) {
a = new Date(a.Date);
b = new Date(b.Date);
return a<b ? -1 : a>b ? 1 : 0;
});
if (data.length > 0) {
$.each(data, function (index, item) {
Aindex = data.indexOf(this)
var h_feedList = '<li';
h_feedList += '><a href="#" onclick="IE_navigate(' + Aindex + ')" target="_blank">';
h_feedList += '<h3>'; // Start Title Text
h_feedList += item.title; // Title Text
h_feedList += '</h3><p>'; // End the title text - start the description text
h_feedList += item.infoDescription; // Description text
h_feedList += '</p>'; // End description text
h_feedList += '</a>'; // End list link
h_feedList += '</li>'; // End List Item
$('#feed').append(h_feedList);
});
}
else
{
var message = "No upcoming events within your selection; check back soon!";
$('#feed').append('<h3>' + message + '</h3>');
}
}
});
};
function next_event() {
Bindex++;
if (Bindex > data.length){ Bindex = 0; }
$('#page-title').html(data[Bindex].title);
$('#page-region').html(data[Bindex].Region);
$('#page-content').html(data[Bindex].fullInfo);
startDate = new Date(data[Bindex].Date);
endDate = new Date(data[Bindex].Date);
title = data[Bindex].title;
place = data[Bindex].Region;
}
function previous_event() {
Bindex--;
if (Bindex <= 0){ Bindex = data.length; }
$('#page-title').html(data[Bindex].title);
$('#page-region').html(data[Bindex].Region);
$('#page-content').html(data[Bindex].fullInfo);
startDate = new Date(data[Bindex].Date);
endDate = new Date(data[Bindex].Date);
title = data[Bindex].title;
place = data[Bindex].Region;
}
$(document).ajaxStart(function() {
$.mobile.loading('show', {text: 'Loading BayArea Events...', textVisible: true, textonly: true});
});
$(document).ajaxStop(function() {
$.mobile.loading('hide');
});
$( document ).on( "pagecreate", "#home", function() {
$( document ).on( "swipeleft swiperight", "#home", function( e ) {
// We check if there is no open panel on the page because otherwise
// a swipe to close the left panel would also open the right panel (and v.v.).
// We do this by checking the data that the framework stores on the page element (panel: open).
if ( $( ".ui-page-active" ).jqmData( "panel" ) !== "open" ) {
if ( e.type === "swipeleft" ) {
$( "#settingspanel" ).panel( "open" );
} else if ( e.type === "swiperight" ) {
$( "#fieldpanel" ).panel( "open" );
}
}
});
});
$( document ).on( "pagecreate", "#eventPage", function() {
$( document ).on( "swipeleft swiperight", "#eventPage", function( e ) {
if ( e.type === "swipeleft" ) {
next_event();
} else if ( e.type === "swiperight" ) {
previous_event();
}
});
});
function Calendar_Add(){
// prep some variables
var startDate = new Date(item.Date);
var endDate = new Date(item.Date);
var title = item.title;
var location = item.region;
var notes = "";
var success = function(message) { alert("Success: " + JSON.stringify(message)); };
var error = function(message) { alert("Error: " + message); };
// create
window.plugins.calendar.createEventWithCalendar(title,location,notes,startDate,endDate,success,error);
}

The function createEventWithCalendar does not exist for the Calendar plugin. You should use createEvent with the same parameters.
You would probably have been warned by a Javascript error if you had a function like this somewhere:
window.onerror = function(a,b,c) {
alert(a);
alert(b);
alert(c);
}
Hope this helps you getting my plugin to work,
Eddy

Related

JavaScript (retrieve data from HTML)

I was trying to retrieve some data from a website (HTML) with JavaScript (node.js). The data I want to retrieve is in a paragraph but the whole paragraph is separated by line breaks and my code only fetch the last paragraph.
I am using this codes
event.Description = $(this)[0]['next'];
How do I get the full paragraph that are broken with line breaks?
var request = require("request");
var cheerio = require("cheerio");
var currentDate = new Date();
var url = "westernsydney.edu.au/observatorypenrith/penrith_observatory/…";
request(url, function (err, responce, html) {
if (!err) {
var $ = cheerio.load(html);
var eventList = new Array();
$('div#content table>thead>tr ').each(function (index, item) {
if (index > 0) {
var event = {
Date: null,
EventName: null,
Description: null,
LinkURL: null,
Year: currentDate.getFullYear()
};
var child = $(this).children();
$(child).each(function (index2) {
var subChildren = $(this).children();
$(subChildren).each(function (index3) {
if (index2 == 0) {
//console.log('Date -', $(this).text());
event.Date = $(this)[0]['next']['data']
} else if (index2 == 1) {
event.EventName = $(this).text();
} else if (index2 == 2) {
event.Description = $(this)[0]['next']['data'];
} else if (index2 == 3) {
event.LinkURL = $(this).attr('href');
}
});
});
eventList.push(event);
}
});
console.log("Events Array", eventList);
}
});

Promises code works in Google Chrome but not in Internet Explorer

I have the following code which reads information from a sharepoint list and renders fine in google chrome, but when tested in IE 11 (Corporate Browser), then I get the following exception:
ReferenceError: 'Promise' is undefined
at getContentTypeOfCurrentItem (https://ourserver.com/sites/billing/Style%20Library/xxx/Angular/related-billing-documents-controller.js:209:5)
at addContentType (https://ourserver.com/sites/billing/Style.com/sites/billing/Style%20Library/xxx/Angular/related-billing-documents-controller.js:201:5)
at Anonymous function (https://ourserver.com/sites/billing/Style%20Library/xxx/Angular/related-billing-documents-controller.js:163:7)
at Anonymous function (https://ourserver.com/sites/billing/Style%20Library/xxx/Angular/angular.min.js:130:399)
at m.prototype.$eval (https://ourserver.com/sites/billing/Style%20Library/xxx/Angular/angular.min.js:145:96)
at m.prototype.$digest (https://ourserver.com/sites/billing/Style%20Library/xxx/Angular/angular.min.js:142:165)
at Anonymous function (https://ourserver.com/sites/billing/Style%20Library/xxx
(function () {
angular
.module('BillCycleApp')
.controller('relatedBillingDocumentsController', ['$scope', '$log', '$q', 'spService', 'BillingDocuments', 'General',
function ($scope, $log, $q, spService, config, generalConfig) {
var vm = this;
var tableSelector = "#related-billing-documents-table";
var componentSelector = ".related-billing-documents";
function GetContext() {
vm.Name = config.Name;
var dataTableColumns = spService.TransformFieldsToDataTableColumns(config.FieldsToShow);
$.fn.dataTable.moment( generalConfig.DateTimeFormat );
// Initialize with empty data
$(tableSelector).DataTable({
data : [],
columns : dataTableColumns,
order : config.SortOrder,
deferRender : true
}).on( 'draw.dt', function ( e, settings, processing ) {
// Make sure the UserPresence is added every time the DataTable's data changes (paging, sorting, search,..)
spService.UserPresenceComponent.AddPresence();
});
// Make component visible
$(componentSelector).css("visibility", "visible");
// SP.js function
// Get Bill Cycle list & id
var listItemId = GetUrlKeyValue('ID', true, window.location.search, true);
var listId = "{" + GetUrlKeyValue('List', true, window.location.search, true) + "}";
var propertiesToLoad = ["FileRef","PwC_ClientCode","PwC_JobCodesMulti","PwC_EngagementCode"];
spService.GetListItem(listId, listItemId, propertiesToLoad)
.then(function(billCycle) {
var listItemValues = [];
propertiesToLoad
.forEach(function(propertyName) {
var value = billCycle.get_item(propertyName);
listItemValues[propertyName] = value;
});
var billCyclePath = _spPageContextInfo.siteAbsoluteUrl;
billCyclePath += listItemValues["FileRef"];
var clientCode = listItemValues["PwC_ClientCode"]
var jobCodesLookups = listItemValues["PwC_JobCodesMulti"];
var engagementCode = listItemValues["PwC_EngagementCode"]
var jobCodes = [];
if(jobCodesLookups) {
jobCodesLookups.forEach(function(lookup) {
jobCodes.push(lookup.get_lookupValue());
});
}
// Get data with parameters
GetData(billCyclePath, clientCode, jobCodes, engagementCode);
});
}
function GetData(billCyclePath, clientCode, jobCodes, engagementCode) {
var enhanceFunctions = [
function(searchResultRow) {
return spService.AddHyperLinkOnFields(searchResultRow, config.HyperLinks);
},
function(searchResultRow) {
return spService.AddPresenceOnFields(searchResultRow, config.UserFields);
},
function(searchResultRow) {
return spService.FormatDateFields(searchResultRow, config.DateFields, generalConfig.DateTimeFormat);
},
function(searchResultRow) {
return spService.AddImageMapping(searchResultRow, config.ImageFields);
},
function(searchResultRow) {
return spService.FormatNumberFields(searchResultRow, config.NumberFields);
},
function(searchResultRow) {
// Put link to parent Bill Cycle with name = folder name
//var parentLink = searchResultRow["FileRef"];
//arrayofstrings = parentLink.split("/");
//var billCycleFolderName = arrayofstrings[arrayofstrings.length-2];
//arrayofstrings.pop();
//var hyperLink = '' + billCycleFolderName + '';
//searchResultRow["Bill Cycle"] = hyperLink;
}
];
// Get data from SP
var selectProperties = spService.TransformFieldsToSelectProperties(config.Fields); // copy array
var selectPropertiesToShow = spService.TransformFieldsToSelectProperties(config.FieldsToShow); // copy array
var extendedSelectProperties = selectProperties.slice();
var hyperLinkedProperties = spService.TransformFieldsToSelectProperties(config.HyperLinks)
extendedSelectProperties = extendedSelectProperties.concat(hyperLinkedProperties);
GetRelatedBillingDocumentsFromList(extendedSelectProperties, billCyclePath, clientCode, jobCodes, engagementCode, enhanceFunctions)
.then(function (data) {
var trimmedData = spService.SpSearchQuery.TrimSearchResultsToSelectProperties(data, selectPropertiesToShow);
// Add data to dataTable
var dataTable = $(tableSelector).DataTable();
dataTable.clear().rows.add(trimmedData).columns.adjust().draw(); // Resize columns based on new data sizes
vm.ValidDataLoaded = true;
})
.catch (function (message) {
vm.Name = "Error";
vm.ValidDataLoaded = true;
});
}
function GetRelatedBillingDocumentsFromList(selectProperties, currentBillCyclePath, clientCode, jobCodes, engagementCode, enhanceFunctions) {
$log.info("Retrieving related billing documents for bill cycle with name [" + currentBillCyclePath + "]");
var deferred = $q.defer();
var webUrl = _spPageContextInfo.webAbsoluteUrl;
selectProperties = selectProperties.concat("ContentTypeId");
var viewFields = spService.ConvertSelectPropertiesToViewFields(selectProperties);
// query must return the documents for the same client but in other bill cycles not the current one
var camlQuery = '<View Scope="RecursiveAll">' + viewFields +
'<Query>' +
'<Where>' +
'<And>' +
'<Eq>' +
'<FieldRef Name="PwC_ClientCode" />' +
'<Value Type="Text">'+ clientCode + '</Value>' +
'</Eq>' +
'<Neq>' +
'<FieldRef Name="ContentType" />' +
'<Value Type="Computed">Bill Cycle</Value>' +
'</Neq>' +
'</And>' +
'</Where>' +
'</Query>' +
'</View>';
var billCyclesListId = "{c23bbae4-34f7-494c-8f67-acece3ba60da}";
spService.GetListItems(billCyclesListId, camlQuery, selectProperties)
.then(function(listItems) {
var listItemsWithValues = [];
if(listItems) {
var enumerator = listItems.getEnumerator();
var promises = [];
while (enumerator.moveNext()) {
var listItem = enumerator.get_current();
var listItemValues = [];
selectProperties
.forEach(function(propertyName) {
var value = listItem.get_item(propertyName);
if(propertyName === "PwC_JobCodesMulti"){
jobvalue = "";
value.forEach(function(jobvalues){
jobvalue+= jobvalues.get_lookupValue() +";";
})
listItemValues[propertyName] = jobvalue;
}else{
listItemValues[propertyName] = value;
}
});
listItemsWithValues.push(listItemValues);
}
var promises = listItemsWithValues.map(addContentType);
Promise.all(promises).then(youCanUseTheData);
function youCanUseTheData(){
/*
At this point, each listItem holds the 'Document Type' info
*/
listItemsWithValues.forEach(function(listItem) {
var fileDirRef = listItem["FileRef"];
var id = listItem["ID"];
var title = listItem["Title"];
var serverUrl = _spPageContextInfo.webAbsoluteUrl.replace(_spPageContextInfo.webServerRelativeUrl,"");
var dispFormUrl = serverUrl + "/sites/billing/_layouts/15/DocSetHome.aspx?id="+fileDirRef;
var parentLink = listItem["FileRef"];
arrayofstrings = parentLink.split("/");
var billCycleFolderName = arrayofstrings[arrayofstrings.length-2];
arrayofstrings.pop();
var hyperLink = '' + billCycleFolderName + '';
listItem["Bill Cycle"] = hyperLink;
listItemsWithValues["Document Type"] = getContentTypeOfCurrentItem(listItem.ID.toString());
});
var enhancedListItemValues = spService.SpSearchQuery.EnhanceSearchResults(listItemsWithValues, enhanceFunctions);
deferred.resolve(listItemsWithValues);
}
}
})
.catch (function (message) {
deferred.reject();
});
return deferred.promise;
}
function addContentType(listItem){
//return getContentTypeOfCurrentItem(listItem.ID.toString());
return getContentTypeOfCurrentItem(listItem.ID.toString()).then(function(cname) {
listItem['Document Type'] = cname; //we add the doc type to each listItem, not only the last one
}).catch(function(error) {
$log.warn("Server error");
});
}
function getContentTypeOfCurrentItem(id) {
return new Promise(function (resolve, reject) {
var clientContext = new SP.ClientContext.get_current();
var oList = clientContext.get_web().get_lists().getByTitle("Bill Cycles");
var listItem2 = oList.getItemById(id);
listContentTypes = oList.get_contentTypes();
clientContext.load(listContentTypes);
clientContext.load(listItem2, 'ContentTypeId');
clientContext.executeQueryAsync(
function() {
$log.info("Successfully retrieved getContentTypeOfCurrentItemt");
var ctid = listItem2.get_item("ContentTypeId").toString();
var ct_enumerator = listContentTypes.getEnumerator();
while (ct_enumerator.moveNext()) {
var ct = ct_enumerator.get_current();
if (ct.get_id().toString() == ctid) {
var contentTypeName = ct.get_name();
}
}
return resolve(contentTypeName);
},
function(error, errorInfo) {
$log.warn("Retrieving getContentTypeOfCurrentItem failed");
return reject(errorInfo);
}
);
});
}
function GetRelatedBillingDocuments(selectProperties, currentBillCyclePath, clientCode, jobCodes, engagementCode, enhanceFunctions) {
$log.info("Retrieving related billing documents for bill cycle with path [" + currentBillCyclePath + "]");
var deferred = $q.defer();
var webUrl = _spPageContextInfo.webAbsoluteUrl;
// TODO: AND or OR?
var jobCodesFilter = spService.ExpandSearchFilterForEachValue("JobCodes", ":", jobCodes, false, false);
var engagementCodeFilter = "";
if (engagementCode != undefined && engagementCode != "") {
engagementCodeFilter = "EngagementCode:" + engagementCode;
}
if(jobCodesFilter && engagementCodeFilter) {
jobCodesFilter += " OR ";
}
// TODO: Add use of result source?
var queryText = "-Path:" + spService.AddQuotes(currentBillCyclePath) + ' AND -ContentType:"Bill Cycle" AND ClientCode:' + clientCode + " AND (" + jobCodesFilter + engagementCodeFilter + ")";
var searchQuery = new spService.SpSearchQuery(webUrl, queryText, selectProperties, config.ResultSourceName, config.ResultSourceLevel);
searchQuery
.ExecuteSearchQueryFetchAll() // returns deferred
.then(function (results) {
$log.info("Successfully retrieved search results");
var searchResults = spService.SpSearchQuery.EnhanceSearchResults(results, enhanceFunctions);
deferred.resolve(searchResults);
});
return deferred.promise;
}
ExecuteOrDelayUntilScriptLoaded(GetContext, 'sp.js');
}
]); // End Controller()
}()); // End IFFE
Promise is part of ES6 standard that is not fully supported by IE11, you can use babel-polyfill instead or use another librairy like q which is part of angularjs

Add background image using Javascript CSS property

I'm trying to add background image using Javascript CSS property. My code does not work. If I add 'url' directly, it worked. Is 'weatherImage' variable a problem..?
Javascript
var OpenWeatherKey = 'API key';
var locationUrl = 'http://freegeoip.net/json/';
function getLocation(){
$.ajax({
url : locationUrl,
dataType: "json",
success : function(data){
var country = data['country_name'];
var city = data['city'];
var latitude = data['latitude'];
var longitude = data['longitude'];
$('#location').html(city + ', ' + country);
var Weather = "http://api.openweathermap.org/data/2.5/weather?lat=" + latitude + "&lon=" + longitude +"&APPID=" +OpenWeatherKey;
getWeather(Weather);
}
});
}
function getWeather(url){
$.ajax({
url:url,
dataType:"json",
success: function(data){
var weather = data['weather'][0]['main'];
var temp = data['main']['temp'];
var icon = data['weather'][0]['icon'];
var id = data['weather'][0]['id'];
document.getElementById('icon').src="http://openweathermap.org/img/w/" + icon + ".png";
$('#weather').html(weather);
$('#temp').html(temp);
// Change F to C, C to F
var fahrenheit = Math.floor((temp) * 9/5 - 459.67) + '\xB0F';
var celsius = Math.floor((temp)- 273.15) + '\xB0C';
var $tempDisplay = $("#temp");
$tempDisplay.html(celsius);
$("#button-f").on('click', function() {
$tempDisplay.html(fahrenheit);
});
$("#button-c").on('click', function() {
$tempDisplay.html(celsius);
});
// change Background image
var imagePhoto = {
thunder: "http://www.tabinotebook.com/wp-
content/uploads/2017/02/jeremy-bishop-72584.jpg",
rainy: "http://www.tabinotebook.com/wp-content/uploads/2017/02/lukas-budimaier-131299.jpg",
cloudy: "http://www.tabinotebook.com/wp-content/uploads/2017/02/odair-faleco-192489.jpg",
snow: "http://www.tabinotebook.com/wp-content/uploads/2017/02/james-padolsey-154227.jpg",
sunny: "http://www.tabinotebook.com/wp-content/uploads/2017/02/tomas-salas-81161.jpg",
}
var weatherImage = "";
function selectImage (id){
if(id >= 200 && id <= 232){
weatherImage = imagePhoto.thunder;}
else if (id >= 300 && id <= 531){
weatherImage = imagePhoto.rainy;}
else if (id >= 600 && id <= 622){
weatherImage = imagePhoto.snow;}
else if (id >= 801 && id <= 804){
weatherImage = imagePhoto.cloudy;}
else if (id === 800){
weatherImage = imagePhoto.sunny;}
else {
weatherImage = imagePhoto.cloudy;}
}
// we set the background first after the weatherImage has been assigned a value
// above
$('body').css('background-image','url(' + weatherImage + ')');
selectImage(800);
}
});
};
getLocation();
Thank you so much in advance.
You need to add the actual contents of the variable weatherImage, right now you're just setting the url to the name of the variable. Try changing your code to:
$('body').css('background-image', 'url(' + weatherImage + ')');
It is a little hard to tell what is not working since you don't have included the entire script and you also don't show how and where you call selectImage(). The following should work though:
// change api key to whatever you are using
var OpenWeatherKey = 'your-api-key';
var locationUrl = 'http://freegeoip.net/json/';
var weatherImage = "";
var imagePhoto = {
thunder: "http://www.tabinotebook.com/wp-content/uploads/2017/02/jeremy-bishop-72584.jpg",
rainy: "http://www.tabinotebook.com/wp-content/uploads/2017/02/lukas-budimaier-131299.jpg",
cloudy: "http://www.tabinotebook.com/wp-content/uploads/2017/02/odair-faleco-192489.jpg",
snow: "http://www.tabinotebook.com/wp-content/uploads/2017/02/james-padolsey-154227.jpg",
sunny: "http://www.tabinotebook.com/wp-content/uploads/2017/02/tomas-salas-81161.jpg"
};
function selectImage (id) {
if(id >= 200 && id <= 232) {
weatherImage = imagePhoto.thunder;
}
else if (id >= 300 && id <= 531) {
weatherImage = imagePhoto.rainy;
}
else if (id >= 600 && id <= 622) {
weatherImage = imagePhoto.snow;
}
else if (id >= 801 && id <= 804) {
weatherImage = imagePhoto.cloudy;
}
else if (id === 800) {
weatherImage = imagePhoto.sunny;
}
else {
weatherImage = imagePhoto.cloudy;
}
// we set the background first after the weatherImage has been assigned a value
// above
$('body').css('background-image','url(' + weatherImage + ')');
}
function getLocation(){
$.ajax({
url : locationUrl,
dataType: "json",
success : function(data){
var country = data['country_name'];
var city = data['city'];
var latitude = data['latitude'];
var longitude = data['longitude'];
$('#location').html(city + ', ' + country);
var Weather = "http://api.openweathermap.org/data/2.5/weather?lat=" + latitude + "&lon=" + longitude +"&APPID=" +OpenWeatherKey;
getWeather(Weather);
}
});
}
function getWeather(url){
$.ajax({
url:url,
dataType:"json",
success: function(data) {
var weather = data['weather'][0]['main'];
var temp = data['main']['temp'];
var icon = data['weather'][0]['icon'];
var id = data['weather'][0]['id'];
document.getElementById('icon').src= "http://openweathermap.org/img/w/" + icon + ".png";
$('#weather').html(weather);
$('#temp').html(temp);
// Change F to C, C to F
var fahrenheit = Math.floor((temp) * 9/5 - 459.67) + '\xB0F';
var celsius = Math.floor((temp)- 273.15) + '\xB0C';
var $tempDisplay = $("#temp");
$tempDisplay.html(celsius);
$("#button-f").on('click', function() {
$tempDisplay.html(fahrenheit);
});
$("#button-c").on('click', function() {
$tempDisplay.html(celsius);
});
// select background image based on id
selectImage(id);
}
});
};
getLocation();

jquery click event for child div not working in plugin

I'm trying to add a click event on each row. On click I need to be able to grab the name (ex. Jeremy) and place in the top div, replacing the question marks. My click event only works on id="data" but not the child divs. I have my code here on codepen as well http://codepen.io/rrschweitzer/pen/GrRyLg?editors=0110. Any help is much appreciated!!
This is my html:
<div id="interview-test">
<div class="top-bars">
<div id="secret">???</div>
<button id="clear">Clear</button>
</div>
<div id="data"></div>
</div>
This is my Jquery:
(function($) {
$.fn.interviewTest = function() {
var self = this;
var testData = null;
var url = "https://private-f3b4b-interview2.apiary-mock.com/data";
// create rows
self.createRow = function(data) {
var theRow = $('<div>').addClass('rows')
.append($('<div>').addClass('image-container')
.append($('<img>').addClass('picture').attr('src', data.image)))
.append($('<div>').addClass('name').append($('<h1>').html(data.name)))
.append(self.getDate(data.timestamp))
return theRow;
}
self.getDate = function(date) {
var date = date.slice(0,-3)
var newdate = new Date(date * 1000)
var year = newdate.getFullYear();
var month = newdate.getMonth();
var day = newdate.getDay()
var formattedDate = month + '/' + day + '/' + year
return formattedDate;
}
// api call
$.ajax({
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', 'Basic ');
},
url: url,
success: function(data, status) {
var dataObject = data;
var i = 0;
var testData = [];
for(var key in dataObject) {
testData[i] = dataObject[key]
i++;
}
// console.log(testData);
self.createDataList(testData, i);
}
})
self.createDataList = function(data, size) {
var rows = $(self).find('#data');
if (size != 0) {
$.each(data, function(key, value) {
// console.log(value)
rows.append(self.createRow(value))
})
}
}
// event listeners
$(self).find('.rows').on('click', function(e) {
var current = $(e.currentTarget);
console.log(current);
// if(current)
})
}}(jQuery))$('#interview-test').interviewTest();
You need to add your event listeners after elements (rows) are created:
(function($) {
$.fn.interviewTest = function() {
var self = this;
var testData = null;
var url = "https://private-f3b4b-interview2.apiary-mock.com/data";
// create rows
self.createRow = function(data) {
var theRow = $('<div>').addClass('rows')
.append($('<div>').addClass('image-container')
.append($('<img>').addClass('picture').attr('src', data.image)))
.append($('<div>').addClass('name').append($('<h1>').html(data.name)))
.append(self.getDate(data.timestamp))
return theRow;
}
self.getDate = function(date) {
var date = date.slice(0,-3)
var newdate = new Date(date * 1000)
var year = newdate.getFullYear();
var month = newdate.getMonth();
var day = newdate.getDay()
var formattedDate = month + '/' + day + '/' + year
return formattedDate;
}
// api call
$.ajax({
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', 'Basic ');
},
url: url,
success: function(data, status) {
var dataObject = data;
var i = 0;
var testData = [];
for(var key in dataObject) {
testData[i] = dataObject[key]
i++;
}
// console.log(testData);
self.createDataList(testData, i);
}
})
self.createDataList = function(data, size) {
var rows = $(self).find('#data');
if (size != 0) {
$.each(data, function(key, value) {
// console.log(value)
rows.append(self.createRow(value))
});
self.addEventListeners()
}
}
self.addEventListeners() {
// event listeners
$(self).find('.rows').on('click', function(e) {
var current = $(e.currentTarget);
console.log(current);
// if(current)
})
}
}}(jQuery))$('#interview-test').interviewTest();
you can use event delegation for this to attach the event with the parent element which will fire for all the matching selector child elements.
$(self).on('click', ".rows",function(e) {
var current = $(this);
if(current)
{
var name = current.find(".name").text();
$("#secret").text(name);
}
})
code pen : http://codepen.io/anon/pen/EZxRwM?editors=0110
Your demo doesn't work however looking at your code you are trying to look for self.find('.rows') before the ajax has completed and the rows have been created
You either need to delegate the event or wait until rows are added in the ajax success

Dynamic content not loading on mobile

This is the page having an issue: http://f6d.28a.myftpupload.com/blog/
All posts on this page are loaded are using a jquery.
The page is working fine on desktop, even on firefox if I test page using ctrl+shift+m for page is working properly.
But when I open this page on my iphone 5s, iOS 8.2, No posts are loading.
Code through which those post are loaded is as below:
jQuery(function($){
var $grid = $('.post-area').masonry({
itemSelector: '.post-area .box',
});
var page = 1;
var loading = true;
var $window = $(window);
var $content = $("body #main");
var load_posts = function( cat = $("input[name='cat_id']").val(), year = '', orderby = '' ){
if((cat != '' || year != '' || orderby != '') && page == 1){
$content.html('');
$content.append('<div id="temp_load" style="text-align:center">\
<img src="http://f6d.28a.myftpupload.com/wp-content/themes/bob/images/ajax-loader.png" />\
</div>');
}
$.ajax({
type : "GET",
data : {numPosts : 1, pageNumber: page, cat: cat, year: year, orderby: orderby},
dataType : "html",
url : "http://f6d.28a.myftpupload.com/wp-content/themes/bob/template-parts/loopHandler.php",
beforeSend : function(){
if(page != 1){
$content.append('<div id="temp_load" style="text-align:center; bottom: 0; left: 0; position: absolute; right: 0;">\
<img src="http://f6d.28a.myftpupload.com/wp-content/themes/bob/images/ajax-loader.png" />\
</div>');
}
},
success : function(data){
$data = $(data);
if($data.length){
$data.hide();
$content.append($data);
$grid.append( $data ).masonry( 'appended', $data );
$grid.masonry( 'reloadItems' );
$grid.masonry( 'layout' );
$data.fadeIn(500, function(){
$("#temp_load").remove();
loading = false;
});
} else {
$("#temp_load").remove();
}
},
error : function(jqXHR, textStatus, errorThrown) {
$("#temp_load").remove();
alert(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
}
$window.scroll(function() {
var content_offset = $content.offset();
console.log(content_offset.top);
if(!loading && ($window.scrollTop() +
$window.height()) > ($content.scrollTop() + $content.height() + content_offset.top)) {
loading = true;
var cat = $('select[name="cat"]').val();
var year = $('select[name="year"]').val();
var orderby = $('select[name="orderby"]').val();
page++;
load_posts( cat, year, orderby );
}
});
$('select[name="cat"]').on('change', function() {
var cat = $(this).val();
var year = $('select[name="year"]').val();
var orderby = $('select[name="orderby"]').val();
page = 1;
load_posts(cat, year, orderby);
});
$('select[name="year"]').on('change', function() {
var year = $(this).val();
var cat = $('select[name="cat"]').val();
var orderby = $('select[name="orderby"]').val();
page = 1;
load_posts(cat, year, orderby);
});
$('select[name="orderby"]').on('change', function() {
var orderby = $(this).val();
var cat = $('select[name="cat"]').val();
var year = $('select[name="year"]').val();
page = 1;
load_posts(cat, year, orderby);
});
load_posts();
});
Can some please guide me on this....

Categories

Resources