Jquery Not Working Windows Universal App - javascript

This is not a duplicate as this has nothing to do with referenced link as this is a windows based application, and has nothing to do with the location of the script as this is not related to a web based app. Please remove duplication.
Maybe I am just putting the code in the wrong location as this is my first time attempting to get started in creating Universal Apps for windows using JS. As per windows developer site Jquery can be used. https://blogs.windows.com/buildingapps/2013/07/10/jquery-and-winjs-working-together-in-windows-store-apps/#IYuzrU7FW7kC0fig.97
so to just test it out I did a standard simple default new project. With some jquery test code.
My Test Jquery Code:
$(".bodytype").on("click", function () {
console.log('Clicked');
$(".bodytype").css("background", "blue");
});
html code in index.html
<div class="bodytype">A Row</div>
The main.js file in the windows app looks like this:
// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232509
(function () {
"use strict";
var app = WinJS.Application;
var activation = Windows.ApplicationModel.Activation;
var isFirstActivation = true;
app.onactivated = function (args) {
if (args.detail.kind === activation.ActivationKind.voiceCommand) {
// TODO: Handle relevant ActivationKinds. For example, if your app can be started by voice commands,
// this is a good place to decide whether to populate an input field or choose a different initial view.
}
else if (args.detail.kind === activation.ActivationKind.launch) {
// A Launch activation happens when the user launches your app via the tile
// or invokes a toast notification by clicking or tapping on the body.
if (args.detail.arguments) {
// TODO: If the app supports toasts, use this value from the toast payload to determine where in the app
// to take the user in response to them invoking a toast notification.
}
else if (args.detail.previousExecutionState === activation.ApplicationExecutionState.terminated) {
// TODO: This application had been suspended and was then terminated to reclaim memory.
// To create a smooth user experience, restore application state here so that it looks like the app never stopped running.
// Note: You may want to record the time when the app was last suspended and only restore state if they've returned after a short period.
}
}
if (!args.detail.prelaunchActivated) {
// TODO: If prelaunchActivated were true, it would mean the app was prelaunched in the background as an optimization.
// In that case it would be suspended shortly thereafter.
// Any long-running operations (like expensive network or disk I/O) or changes to user state which occur at launch
// should be done here (to avoid doing them in the prelaunch case).
// Alternatively, this work can be done in a resume or visibilitychanged handler.
}
if (isFirstActivation) {
// TODO: The app was activated and had not been running. Do general startup initialization here.
document.addEventListener("visibilitychange", onVisibilityChanged);
args.setPromise(WinJS.UI.processAll());
}
isFirstActivation = false;
};
function onVisibilityChanged(args) {
if (!document.hidden) {
// TODO: The app just became visible. This may be a good time to refresh the view.
}
}
app.oncheckpoint = function (args) {
// TODO: This application is about to be suspended. Save any state that needs to persist across suspensions here.
// You might use the WinJS.Application.sessionState object, which is automatically saved and restored across suspension.
// If you need to complete an asynchronous operation before your application is suspended, call args.setPromise().
};
//Code Here
$(".bodytype").on("click", function () {
console.log('Clicked');
$(".bodytype").css("background", "blue");
});
//App Start Code Before
app.start();
})();
index.html full code here:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>App3</title>
<link href="lib/winjs-4.0.1/css/ui-light.css" rel="stylesheet" />
<script src="lib/winjs-4.0.1/js/base.js"></script>
<script src="lib/winjs-4.0.1/js/ui.js"></script>
<link href="css/default.css" rel="stylesheet" />
<script src="js/jquery-3.1.1.js"></script>
<script src="js/main.js"></script>
</head>
<body class="win-type-body">
<div class="bodytype">A Row</div>
</body>
</html>
can someone help me understand what I am doing wrong? There are no compile errors and the app loads fine, but when I attempt to click the row the background color does not change.

Make sure you already attached your Jquery file in your html page
Goto your main.js and write this
window.onload = function () {
$(".bodytype").on("click", function () {
console.log('Clicked');
$(".bodytype").css("background", "blue");
});
}
`
Worked for me , Fam it will for you too.

Related

Are all these multiple checks really required to handle a new service worker update?

I am following a tutorial on service workers on Udacity by Jake Archibald, and this is the solution skeleton of an exercise on "updating" that has confused me:
They give a long solution that is like the code below (they check for three possible cases, as explained in comments):
(async() => {
if ("serviceWorker" in navigator) {
try {
const reg = await navigator.serviceWorker.register("/sw.js");
if (!reg || !navigator.serviceWorker.controller) {
return;
}
// Possible states of new updates:
// - 1. There are no updates yet, a new update may arrive
// - 2. An update is in progress
// - 3. A waiting update exists (already installed)
// 1.
addEventListener("updatefound", () => {
console.log("updatefound");
const sw = reg.installing;
trackInstallation(sw);
});
// 2
const installingSw = reg.installing;
if (installingSw) {
console.log("installingSw");
trackInstallation(installingSw);
return;
}
// 3
if (reg.waiting) {
console.log("reg.waiting");
const sw = reg.waiting;
notifyUpdate();
return;
}
console.log("nothing");
} catch (error) {
console.error("Service worker registration failed.", error);
}
}
})();
function trackInstallation(worker) {
worker.addEventListener("statechange", () => {
if (worker.state === "installed") {
notifyUpdate();
}
});
}
function notifyUpdate() {
alert("There's a new update!");
}
But I tried different scenarios and I can't get these checks except the third one (if (reg.waiting) {) to be triggered. So I wonder if all these checks are really needed?
This is how I trigger the third check:
Install the service worker (register, install, activate) by loading the web page for the first time at localhost:8080
Make a change to the service worker (e.g., add "/tmp.txt" to the array of names of the files that have to be cached)
Refresh the page.
👉 First load none of the checks are triggered.
👉 Second load, reg.waiting runs (the third check is triggered).
which makes sense (I've read and I know how the lifecycle of service workers works), but I don't know in what scenario the other two checks (i.e., the ones on line 14 and 21) would be triggered?
Things to remember:
The service worker isn't for a single page
The service worker runs independently of any page
In your example code, one page installs the service worker, and ensures that the install completes entirely.
That isn't always the case in the real world. Let's say:
You refresh a service-worker-controlled page.
That triggers a service worker update check. Assuming an update is found:
// 1 will happen for all pages in the origin. You might not be seeing it, because your code is addEventListener('updatefound', where it should be navigator.serviceWorker.addEventListener('updatefound'.
If at this point, you reload the page, you might hit // 2, since there's already an install in progress.
For more details on the service worker lifecycle, see https://web.dev/service-worker-lifecycle/

Electron "ready-to-show" event not working as expected

Here is a block of code from my application Codey.
src/main.py
// Show window once it has finished initialising
docsWindow.once("ready-to-show", () => {
if (darkMode) {
docsWindow.webContents.send("dark-mode:toggle");
}
if (!isDarwin) {
docsWindow.webContents.send("platform:not-darwin");
}
docsWindow.webContents.send("docs:jump", section);
docsWindow.show();
});
src/docs/renderer.js
window.api.darkMode.toggle.receive(toggleDarkMode);
When darkMode = true, toggleDarkMode is never run.
My application has two different windows - an editor and a docs window. For both windows, on the "ready-to-show" event, "dark-mode:toggle" is sent to the renderer process. However, the docs window fails to run the toggleDarkMode function whilst it works for the editor window.
Note: The application must be packaged using "yarn package" as some features do not work in the dev environment.
Any help will be much appreciated.
(Repo: https://github.com/Liamohara/Codey)
For anyone that's interested. I found a solution to my issue.
src/main.py
// Show window once it has finished initialising
- docsWindow.once("ready-to-show", () => {
+ docsWindow.webContents.once("did-finish-load", () => {
if (darkMode) {
docsWindow.webContents.send("dark-mode:toggle");
}
if (!isDarwin) {
docsWindow.webContents.send("platform:not-darwin");
}
docsWindow.webContents.send("docs:jump", section);
docsWindow.show();
});
In the docs window, there is more HTML content to be renderered than in the editor window. As a result, the DOM takes longer to load and the "ready-to-show" event is emitted before it has finished. Using the "did-finish-load" event, ensures that the API functions are not called before the DOM has finished loading.

How to launch uwp webview app in full screen mode by default

We have created a full fledged UWP webview app (WinJs) with help of Visual Studio 2017. Recently going through microsoft documentation and stackoverflow threads, we found out that the uwp app can be launched full screen with title bar removed.
Following code needed to inserted into App.Xaml.Cs file
ApplicationView view = ApplicationView.GetForCurrentView();
view.TryEnterFullScreenMode();
But the problem here is that, we are unable to locate this file to insert this. May be its because of WinJS template i have chosen, i don't know.
Other notables files include main.js | packageapp.manifest file. I do not know whether this code could be integrated with either of this file.
Edit:
With roy's help, the main js file is modified according to the sample given in windows universal sample github, but still full screen does not seem to open up.
The main.js file code is as given below
(function () {
"use strict";
var app = WinJS.Application;
var activation = Windows.ApplicationModel.Activation;
var isFirstActivation = true;
var ViewManagement = Windows.UI.ViewManagement;
var ApplicationViewWindowingMode = ViewManagement.ApplicationViewWindowingMode;
var ApplicationView = ViewManagement.ApplicationView;
function onLaunchInFullScreenModeChanged() {
ApplicationView.preferredLaunchWindowingMode = launchInFullScreenMode.checked ? ApplicationViewWindowingMode.fullScreen : ApplicationViewWindowingMode.auto;
}
app.onactivated = function (args) {
if (args.detail.kind === activation.ActivationKind.voiceCommand) {
// TODO: Handle relevant ActivationKinds. For example, if your app can be started by voice commands,
// this is a good place to decide whether to populate an input field or choose a different initial view.
}
else if (args.detail.kind === activation.ActivationKind.launch) {
launchInFullScreenMode.addEventListener("click", onLaunchInFullScreenModeChanged);
launchInFullScreenMode.checked = ApplicationView.preferredLaunchWindowingMode == ApplicationViewWindowingMode.fullScreen;
// A Launch activation happens when the user launches your app via the tile
// or invokes a toast notification by clicking or tapping on the body.
if (args.detail.arguments) {
// TODO: If the app supports toasts, use this value from the toast payload to determine where in the app
// to take the user in response to them invoking a toast notification.
}
else if (args.detail.previousExecutionState === activation.ApplicationExecutionState.terminated) {
// TODO: This application had been suspended and was then terminated to reclaim memory.
// To create a smooth user experience, restore application state here so that it looks like the app never stopped running.
// Note: You may want to record the time when the app was last suspended and only restore state if they've returned after a short period.
}
}
if (!args.detail.prelaunchActivated) {
// TODO: If prelaunchActivated were true, it would mean the app was prelaunched in the background as an optimization.
// In that case it would be suspended shortly thereafter.
// Any long-running operations (like expensive network or disk I/O) or changes to user state which occur at launch
// should be done here (to avoid doing them in the prelaunch case).
// Alternatively, this work can be done in a resume or visibilitychanged handler.
}
if (isFirstActivation) {
// TODO: The app was activated and had not been running. Do general startup initialization here.
document.addEventListener("visibilitychange", onVisibilityChanged);
args.setPromise(WinJS.UI.processAll();
launchInFullScreenMode.addEventListener("click", onLaunchInFullScreenModeChanged);
launchInFullScreenMode.checked = ApplicationView.preferredLaunchWindowingMode == ApplicationViewWindowingMode.fullScreen;
}
isFirstActivation = false;
};
function onVisibilityChanged(args) {
if (!document.hidden) {
// TODO: The app just became visible. This may be a good time to refresh the view.
}
}
app.oncheckpoint = function (args) {
// TODO: This application is about to be suspended. Save any state that needs to persist across suspensions here.
// You might use the WinJS.Application.sessionState object, which is automatically saved and restored across suspension.
// If you need to complete an asynchronous operation before your application is suspended, call args.setPromise().
};
app.start();
})();
Any suggestions on how to solve this problem.
You could put the code in a JS file that will be referenced by the HTML that you are showing.
There used to be a JS UWP FullScreenMode Sample here: FullScreenMode JS. Although it is archived, you could still take a look at scenario2-launch.js and scenario1-basic.js. It shows how to these APIs are used in JavaScript.

Quitting an electron app after setInterval() from external script file

Edited for more clarity.
I am trying to make a splash screen applet - to start learning nodejs and electron.
I want to create an applet that launches, shows some messages every 10 seconds, and then quits.
I'm basing it off the Discord app and Teams where they have pop up loading screens that have a progress bar, and once completed load the full application.
I want to know how to do it before the "load full app" portion kicks in and how to close the splash screen completely.
Currently I have an index.js, index.html, and a main.js.
index.js is the electron browser window. index.html is the main rendered page, and the main.js is the timer to switch the innerHTML based on the time from:
// main.js
var startTime = 0,
totalTime = 10,
timeBuffer = 2,
totalPercent = 0,
timeCounter = setInterval( progress, 1000 );
function progress() {
if( (startTime += 1) >= (totalTime + timeBuffer + 1) ) {
// quit app (1)
} else {
// show messages here
}
}
At point (1) in the code, I've tried adding in app.close(); but that fails since I haven't added in app. I tried adding it in but that doesn't work either.
I tried adding in:
// main.js
const { ipcRenderer } = require('electron');
ipcRenderer.send('close-me');
//index.js
ipcMain.on( 'close-me', (evt, arg) => {
app.quit();
});
But this didn't work either. I'm still trying to understand the relationship between index.js and the other scripts you might write for the app - but thought quitting the app entirely would be easy.
It seems app.quit() wasn't working in this instance, but app.close(0) was.
Reading through the docs didn't suggest any reasons to why but in case someone else runs into this problem too.
Store your setInterval()as a variable and use JavaScript clearInterval(variable) as a page exit action.

Cordova backbutton breaking application

I have a problem with Cordova's android application based on Angular 5+. I've found that window.history.back() and similar native JS back functions make two problems:
when going back, a page is flashing. It seems like first, all HTML content loaded and after it CSS
In one page on a back action, my layout is broken (screens below)
Orginal view:
After back button:
What's curious - after changing phone orientation all backs to normal.
I've found a solution - instead of using vanilla JS back functions I've created mine using Angular Router:
I've subscribe on router's events and save all routes:
this._subs.push(this._router.events.subscribe((e) => {
if (e instanceof NavigationEnd) {
this._cordovaService.saveRoute(e.url);
}
}));
And if I want back, I use navigateByUrl function:
back(): void {
const lastRoute = this._routingHistory[this._routingHistory.length - 2];
if (lastRoute) {
this._router.navigateByUrl(lastRoute);
this._routingHistory.pop();
}
}
After implementing this functionality for my inApp back buttons all work fine - there is no flashing or breaking layout.
Although, after implemented this function for my physical back button, the error is the same - layout breaking or flashing. Below my implementation:
Service:
this.deviceReady = Observable.fromEvent(document, 'deviceready').publishReplay(1);
(this.deviceReady as ConnectableObservable<Event>).connect();
this.restore = Observable.fromEvent(document, 'resume').publishReplay();
(this.restore as ConnectableObservable<Event>).connect();
this.backbutton = Observable.fromEvent(document, 'backbutton').publishReplay();
(this.backbutton as ConnectableObservable<Event>).connect();
Using it:
this._subs.push(this._cordovaService.deviceReady.subscribe(
() => {
document.addEventListener('backbutton', function (e) {
e.preventDefault();
e.stopPropagation();
this._cordovaService.back();
}.bind(this), false);
}
)
);
I'm sure that function in backbutton is executed (I've logged some information) but the problem still occurs.
More information:
I'm using cordova version 8.0.0
I'm using the following plugins:
https://github.com/TheMattRay/cordova-plugin-wkwebviewxhrfix.git" />
Some hints:
Once, I've built Cordova's android applications which work great (with native JS back function) but after next build, all come back. In hockeyapp I see that in good working version lowest available Android version was 4.1. In new apps, it is 4.4.
I've tried to downgrade Cordova/android engine version but without any positive results.
Additionally, I want to work with the newest libraries available.
Thanks for any help in that case.
I've finally found the solution, based on the following blog's post: http://weblogs.thinktecture.com/thomas/2017/02/cordova-vs-zonejs-or-why-is-angulars-document-event-listener-not-in-a-zone.html, I've added below script just before cordova.js import:
<script>
(function () {
'use strict';
window.addEventListener = function () {
EventTarget.prototype.addEventListener.apply(this, arguments);
};
window.removeEventListener = function () {
EventTarget.prototype.removeEventListener.apply(this, arguments);
};
document.addEventListener = function () {
EventTarget.prototype.addEventListener.apply(this, arguments);
};
document.removeEventListener = function () {
EventTarget.prototype.removeEventListener.apply(this, arguments);
};
})();
</script>
<script type="text/javascript" src="cordova.js"></script>
More about why this error occurring you can read in this GitHub issue: https://github.com/angular/angular/issues/22509

Categories

Resources