Phonegap onDeviceOnline - javascript

I am using the folowing script to check if device is online or offline:
function checkConnection() {
document.addEventListener("online", onDeviceOnline, false);
document.addEventListener("offline",onDeviceOffline, false);
function onDeviceOnline(){
loadZive();
loadMobil();
loadAuto();
};
function onDeviceOffline(){
alert("deviceIsOffline");
};
};
checkConnection();
Then I have this function to load feed:
function loadZive(publishedDateConverted){
google.load("feeds", "1");
function initialize() {
var feed = new google.feeds.Feed("http://www.zive.sk/rss/sc-47/default.aspx");
feed.setNumEntries(window.localStorage.getItem("entriesNumber"));
feed.load(function(result) {
if (!result.error) {
var feedlist = document.getElementById("feedZive");
for (var i = 0; i < result.feed.entries.length; i++) {
var li = document.createElement("li");
var entry = result.feed.entries[i];
var A = document.createElement("A");
var descriptionSettings = window.localStorage.getItem("descriptionSettings");
if (descriptionSettings=="true"){
var h3 = document.createElement("h3");
var p = document.createElement("p");
var pDate = document.createElement("p");
pDate.setAttribute("style","text-align: right; margin-top: 5px;");
var publishedDate = new Date(entry.publishedDate);
publishedDateConverted = convertTime(publishedDate);
pDate.appendChild(document.createTextNode(publishedDateConverted));
h3.setAttribute("style","white-space: normal;")
h3.appendChild(document.createTextNode(entry.title));
p.setAttribute("style","white-space: normal;")
p.appendChild(document.createTextNode(entry.content));
A.setAttribute("href",entry.link);
A.appendChild(h3);
A.appendChild(p);
A.appendChild(pDate);
}
else{
A.setAttribute("href",entry.link);
A.setAttribute("style","white-space: normal;")
A.appendChild(document.createTextNode(entry.title));
};
li.appendChild(A);
feedlist.appendChild(li);
}
$("#feedZive").listview("refresh");
}
});
}
google.setOnLoadCallback(initialize);
};
First I load second script, then first. But I cant see anything. If I turn my app on then I see page layout for abou 1 sec then (probably after loading first script) function onDeviceOnline() happens and I can see only blank page. But it should load feeds into existing template.
IMHO onDeviceOnline function happens after loading the page template and therefore it cant import feeds. If I create function like this:
function loadFeeds(){
loadZive();
loadMobil();
loadAuto();
};
then everything works fine so I think it has something to do with online and offline eventlisteners. It also didnt work when I put checkconnection into onDeviceReady function so it should not be the problem. So is there any way to check if device is online and if it is then use js file to load feeds?
EDIT: I have used Simon McDonald suggestion and created code like this:
function onDeviceReady(){
document.addEventListener("backbutton", onBackKeyDown, false);
function onBackKeyDown(){
navigator.app.exitApp();
}
function checkConnection() {
var networkState = navigator.network.connection.type;
if (networkState == "none"){
alert("no network connection");
}
else{
loadZive();
loadMobil();
loadAuto();
};
};
checkConnection();
};
With this code alerts are working perfectly for device online and device offline but when I try to loadFeed I get the same result as before (page layout loads and then everything changes to blank page).

The problem is that you are adding a "online" event listener in device ready event listener but the device is already on line so the event will not fire again until there is a change in connectivity. In your device ready event listener you should check the value of navigator.connection.network.type and make sure it isn't NONE.
http://docs.phonegap.com/en/2.0.0/cordova_connection_connection.md.html#connection.type

Related

How to code for onMouseOver event in Autodesk Forge

I have created a simple extension in autodesk forge.
The idea is that when I make a mouse-over event on a 3D object it has to show me the ID of the hovered object/sub-object my extension code runs like this.
AutodeskNamespace("Autodesk.ADN.Viewing.Extension");
Autodesk.ADN.Viewing.Extension.MouseEvent = function (viewer, options) {
Autodesk.Viewing.Extension.call(this, viewer, options);
var _self = this;
var _viewer = viewer;
var _selectedId = null;
//On Load of the exension function
_self.load = function () {
_viewer.addEventListener(
Autodesk.Viewing.MOUSE_OVER_EVENT,
_self.onMouseOver);
console.log("Autodesk.ADN.MouseEvent loaded");
return true;
};
//On unload of the exension function
_self.unload = function () {
_viewer.removeEventListener(
Autodesk.Viewing.MOUSE_OVER_EVENT,
_self.onMouseOver);
console.log("Autodesk.ADN.MouseEvent unloaded");
return true;
};
// Event function initialization
_self.onMouseOver = function (event) {
var dbId = event.dbIdArray[0];
if (typeof dbId !== 'undefined') {
_selectedId = dbId;
alert('ID: ' + _selectedId);
}
else _selectedId = null;
}
};
Autodesk.ADN.Viewing.Extension.MouseEvent.prototype =
Object.create(Autodesk.Viewing.Extension.prototype);
Autodesk.ADN.Viewing.Extension.MouseEvent.prototype.constructor =
Autodesk.ADN.Viewing.Extension.MouseEvent;
Autodesk.Viewing.theExtensionManager.registerExtension(
'Autodesk.ADN.Viewing.Extension.MouseEvent',
Autodesk.ADN.Viewing.Extension.MouseEvent);
but the onMouseOver function is not working, can anyone please help me? thanks in advance.
PS: I have included the extensions in the script tags and the extension is loaded likewise.
oViewer.loadExtension('Autodesk.ADN.Viewing.Extension.MouseEvent');
I also get a confirmation from the console that the extension is loaded successfully.
There is no such event as Autodesk.Viewing.MOUSE_OVER_EVENT ... did you just made that up or you got it from some - apparently incorrect - source?
The way to handle that would be to use a viewer tool (see that post for details), then in handleMouseMove callback, do the following:
handleMouseMove (event) {
var hitTest = _self.viewer.clientToWorld(
event.canvasX,
event.canvasY,
true)
if (hitTest) {
console.log(hitTest)
}
}
Here is another post I wrote about viewer events, it is a bit old, so there are a couple more now but can give you a good starting point.

Navigate to webpages and click button

Using a simple javascript snippet on google chrome, I am attempting to navigate to various webpages and downloading select files from them.
Here is my code so far..
var thumbnails= document.getElementsByClassName('mythumbnails')
var arr=Array.prototype.slice.call(thumbnails)
timeToCloseWindow=10000;
function work() {
if(thumbnails.length==0) return;
var url = arr.shift();
var openWindow = window.open(url.href);
setTimeout(function () {
document.getElementsByClassName("download-icon")[0].click()
openWindow.close();
work();
}, timeToCloseWindow);
}
work()
Unfortunately, I run into the error Cannot read property 'click' of undefined. I have also tried using a for loop with a sleep condition with the same error. Any idea what I am doing wrong?
window.location = url.href;
document.getElementsByClassName("download-icon")[0].click()

Call Javascript After Saving Calendar Item

I am having a script as below:-
function getColorValue(aId,atitle) {
try{
var clientContext = new SP.ClientContext();
var oWebsite = clientContext.get_web();
var oList = oWebsite.get_lists().getByTitle('Item type');
var oListItem = oList.getItemById(parseInt(aId));
clientContext.load(oListItem);
clientContext.executeQueryAsync(function () {
var listItem = oListItem;
var colorname = listItem.get_item('Color_x0020_Name');
if (typeof colorname != 'undefined') {
if (colorname != null) {
$("div[title$='" + atitle + "']").css("background-color", colorname);
}
}
}, onColorQueryFail);
}
catch(e){
}
}
I need to call this script each time after a SharePoint Calendar Item is created.
Can anyone help?
The following JavaScript example demonstrates how to register event that will be triggered after Calendar item is created:
//custom handler that will be triggered after Calendar item is created
function onEventCreated(){
alert('Event has been created...');
}
function registerCalendarEventOnItemCreated(event)
{
var currentCtx = getCurrentContextInfo();
var calContainer = SP.UI.ApplicationPages.CalendarInstanceRepository.lookupInstance(currentCtx.ctxId);
for(var name in calContainer) {
if(calContainer.hasOwnProperty(name)) {
var p = calContainer[name];
if(p instanceof SP.UI.ApplicationPages.CalendarNewFormDialog) {
p.get_events().addHandler("newitemcreated",event);
}
}
}
}
//get current context info
function getCurrentContextInfo()
{
var currentListId = new SP.Guid(_spPageContextInfo.pageListId);
for(var ctxKey in g_ctxDict){
var curCtx = g_ctxDict[ctxKey];
if(curCtx.listName == currentListId.toString()){
return curCtx;
}
}
return null;
}
//register Calendar events
$('body').on('click', 'div#AsynchronousViewDefault_CalendarView', function() {
registerCalendarEventOnItemCreated(onEventCreated);
});
Has been tested against SharePoint 2013/Online
In your case the function getColorValue could be invoked from onEventCreated, for example:
function onEventCreated(){
getColorValue (id,title);
}
How to apply changes
Switch the page into Edit mode
Add Script Editor webpart into page.
Put the specified code by wrapping it using script tag code into the Script Editor, for example: <script type="text/javascript">{JavaScipt code goes here}</script>
Save the page
Results
Create an Event Receiver with List Item Events for type and Calendar for Source then check 'An item is being added' in handling the event.
Then in the code behind of your Event Receiver:
public override void ItemAdding(SPItemEventProperties properties)
{
base.ItemAdding(properties);
//Call your function through this
Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "MyFunction()", true);
}
Hope that helps :)
I know this is an old question, but there is an issue with the solution given.
I had a requirement to implement an workaround to the missing Resource Reservation feature in Sharepoint online. It was not possible to use an approach more suitable to the Modern Experience, due its dependency of Azure (no Azure subscription available for it), so I use Sharepoint API calls to perform the the same functionality of Resource Reservation.
To use the Sharepoint API, some Ajax calls were needed. But I observed that two calls were executed for each request.
The point is when you register calendar events, it is needed to attach the click event using one, as seen below, to prevent the click event to be fired more than once.
//register Calendar events
$('body').one('click', 'div#AsynchronousViewDefault_CalendarView', function() {
registerCalendarEventOnItemCreated(onEventCreated);
});

PhoneGap/Cordova Plugin - how to set up?

Ive installed the Calendar plugin for iOS successfully (I think) from here:
https://github.com/phonegap/phonegap-plugins/tree/master/iOS/CalendarPlugin
However I just cant seem to get it working.
So far heres what I have done:
Dropped the calendar .h and .m files into the plugins folder of my
project.
Added the calendar.js file to my directory structure and linked in
the header
Added the EventKit and EventKitUI frameworks to my project
Added the term calendarPlugin to my cordova.plist file
And 5. Added the code below to the page one which I want to save:
window.plugins.calendarPlugin.prototype.createEvent = function(title,location,notes, startDate, endDate){
var title= "My Appt";
var location = "Los Felix";
var notes = "me testing";
var startDate = "2012-11-23 09:30:00";
var endDate = "2012-11-23 12:30:00";
cal.createEvent(title,location,notes,startDate,endDate);
}
$(document).ready(function() {
cal = window.plugins.calendarPlugin;
var cal;
$('.calinfo').live('click', function() {
var desiredValue = $(this).parent().prev().find('.calendar').val();
console.log(desiredValue);
var calInfo = desiredValue.split(',');
createEvent(calInfo[0], calInfo[1], calInfo[2], calInfo[3], calInfo[4]);
});
});
When I run it noting happens. Have I missed something?
Dont't use $(document).ready(function());. Rather use device ready. Call the function onBodyLoad() on body load.
function onBodyLoad()
{
document.addEventListener("deviceready", onDeviceReady, false);
deviceready = true;
}
//////////////////////////////////
function onDeviceReady()
{
// Your code goes here
}

function will not call another function, javascript

For a class project i am trying to count the number of clicks a button gets, save the search term, and then open a new html file. my problem is that the "doCoolThings" function will not call the "newWindow" function. I cannot figure out how to get the newWindow function to execute after i click submit.
here is my code:
window.onload = init;
function init() {
var myButton = document.getElementById("submitButton");
myButton.onclick = doCoolThings;
}
function doCoolThings(){
alert("test count");
localStorage.searchTerms = document.getElementById("searchWord").value;
//var searchOutput = document.getElementById("searchOutput");
searchWord.innerHTML = searchTerms;
if (localStorage.clickcount)
{
localStorage.clickcount=Number(localStorage.clickcount)+1;
//window.open("scroogleresults.html");
}
else
{
localStorage.clickcount=1;
//window.location="scroogleresults.html";
}
var myCounter = document.getElementById("numberClicks");
var counter = localStorage.clickcount;
myCounter.innerHTML = counter;
newWindow();
}
function newWindow(){
alert("new window");
window.open("scroogleresults.html");
}
If this is the extent of your code, it looks to me like you have some javascript errors. You should be checking the error console or debug console in your browser for javascript errors that cause your scripts to abort. Here are a couple errors I see:
Error #1
In doCoolThings(), when you do this:
searchWord.innerHTML = searchTerms;
I don't see any place that searchTerms is defined so this would generate a script error.
Error #2
You should be using getItem() and setItem() to access localStorage.

Categories