How to display this JavaScript message in my webOS app? - javascript

I am writing a webOS app and I want the following code to present a "Good Morning!" message. What code do I need to put in my Main-scene.html file and what else do I need in the Main-assistant.js file to make this work?
Many thanks in advance.
MainAssistant.prototype.welcomeMessage = function(){
datetoday = new Date();
timenow = datetoday.getTime();
datetoday.setTime(timenow);
thehour = datetoday.getHours();
if (thehour > 18)
display = "Evening";
else
if (thehour > 12)
display = "Afternoon";
else
display = "Morning";
var greeting = ("Good " + display + "!");
document.write(greeting);
};
All the best
David

I don't know when the welcomeMessage method will be called, but if it's after the document has finished loading then it is closed. Calling document.write then will call document.open, which completely clears the document. Likely you have an element that the message should be written into, much better to use the load or DOMReady events (or whatever is available on WebOS).
Consider a much simpler form of the function and don't forget to declare variables to limit their scope to only what is necessary:
var tod = ['morning','morning','afternoon','evening'];
var now = new Date();
var greeting = 'Good ' + (tod[now.getHours()/6|0]) + '!';
If you want a library, try myLibrary. No, it's not my Library, it's your library when you use it. You can create a customised core and just the DOM ready part that is quite small and the code quality is excellent.

Related

response.getselectedbutton() is not a function?

I am in school and trying to code a google apps script where I have a function bound to a doc with a custom menu that can create a new doc with the date, subject, and email it to the teacher of said subject. All was going according to plan until I decided to make it so that if I hit cancel instead of OK in one of the parameters I would get the default value of that parameter if I had not hit edit parameters so I could easily only change 1 or 2 things. The function works spotlessly, but now what's happening is I can't get the selected button for the alert that asks me if I want to edit parameters.
It just says
"TypeError: response.getSelectedButton is not a function"
and won't let me run my function. Here's my code for the function. This has worked fine for me in the past and I'm really not sure why it doesn't work now.
function Mathdoc() { var ui = DocumentApp.getUi();
var d = new Date();
var s = (d.getDate()) + '/' + (d.getMonth()+1) + '/' + d.getFullYear();
console.log(s);
var response = ui.alert( 'Change parameters?', ui.ButtonSet.YES_NO);
if (response.getSelectedButton() == ui.Button.YES) { insert all my other code here}
Is there a glitch or something I'm missing? I'm new to JS and fairly new to web design altogether.
There is no method named getSelectedButton(). The ui.alert() just returns the button and nothing else
function Mathdoc() {
var ui=DocumentApp.getUi();
var d = new Date();
var s = (d.getDate()) + '/' + (d.getMonth()+1) + '/' + d.getFullYear();
console.log(s);
var response=ui.alert( 'Change parameters?', ui.ButtonSet.YES_NO);
if (response==ui.Button.YES) { insert all my other code here}
Look at example here
Nope, this function doesn't exist. Basically if you type a function on google and don't find anything, it means the function doesn't exist
EDIT : If you have an error message that says it doesn't exist, it means that the function really doesn't exist or that the library containing the function is missing. But in your case the function doesn't exist

Why/How is my code causing a memory leak?

I have written the following JavaScipt code within a Spotfire TextArea. I include the application and tag for completeness, but I don't believe my issue is Spotfire-specific. Essentially, I have a timer which runs every 5 minutes, and clicks on a link (clickLink('Foo');) to trigger execution of some Python code elsewhere in the application. If the application also contains a timestamp of the last full update, which occurs every 30 minutes in the same manner (clickLink('Foo');):
function reportTimestamp() {
var timeNow = new Date();
var hoursNow = timeNow.getHours();
var minutesNow = timeNow.getMinutes();
var secondsNow = timeNow.getSeconds();
return hoursNow + ":" + minutesNow + ":" + secondsNow;
};
function timeBasedReaction(timestampAge){
if (timestampAge >= 1800) {
clickLink('Foo');
clickLink('Bar');
} else if (timestampAge >= 300) {
clickLink('Foo');
};
};
/*
function timeBasedReaction_B(timestampAge){
if (timestampAge >= 300) {
clickLink('Foo');
if (timestampAge >= 1800) {
clickLink('Bar');
};
};
};
*/
function clickLink(linkName) {
var clickTarget = document.getElementById(linkName).children[0];
clickTarget.click();
};
function checkTimestampAge() {
console.log(reportTimestamp());
var myTimeStamp = document.getElementById('Timestamp').children[0]
var timeStampMS = new Date(myTimeStamp.textContent).getTime();
var currentDateMS = new Date().getTime();
var timestampAgeSeconds = (currentDateMS - timeStampMS)/1000;
timeBasedReaction(timestampAgeSeconds);
};
function pageInitialization() {
checkTimestampAge();
var myTimer = null;
var timerInterval = 300000;
myTimer = setInterval(function(){checkTimestampAge()},timerInterval);
}
pageInitialization();
For reasons unclear to me, running this code in the application or in a web browser starts off fine, but eventually leads to very large memory allocation.
I've tried to read
4 Types of Memory Leaks in JavaScript and How to Get Rid Of Them,
JS setInterval/setTimeout Tutorial, and
An interesting kind of JavaScript memory leak, and it's a start, but I don't know enough to really understand what I'm doing wrong and how to correct it.
Thanks, and sorry for the huge block of text.
This causes a memory leak because of how Spotfire handles Javascript which has been associated with/loaded into a TextArea.
Both in the desktop client, as well as in the Webplayer instance, when the page is loaded, all the portions of that page are loaded, include the TextArea and including the Javascript associated therein. My previous understanding in the comments above:
"the code is intended to run when the page loads, and it was my understanding that it would stop/be cleared if the page was re-loaded or someone navigated away from it"
was incorrect. One of the script's actions was to update/redraw the HTML location in the TextArea. This, in turn, reloads the TextArea but does not clear the existing Javascript code. However, it's not really accessible anymore, either, since var myTimer = null actually creates a new myTimer rather than nulling-out the existing one. In this way, instances of myTimer increase geometrically as instances of function timeBasedReaction run and continually update the underlying TextArea and load in more of the same Javascript.
To anyone who ha a similar issue and come here, it's been over 3 months and I haven't figured out how to solve this once and for all. If I do, I'll try to come back with another update.

How do I make a button reusable?

I am relatively new to the world of programming. I have a sturdy knowledge of HTML and CSS, and recently picked up JavaScript. I am working on a series of text generators as a school project; my goal is to be able to, on the website, click a button and have the computer spit out random text each time you click the button. However, while I have a good grasp on HTML and JavaScript, my knowledge on how to combine the two to give a webpage functionality is virtually nonexistent.
I created a "Shakespearean Insult Generator" using JavaScript, which is functional, and I figured out how to add a button to a page so that when you click the button, it prints a randomly generated insult to the page:
<script>
var adjective1 = ["artless", "bawdy", "beslubbering"...
var adjective2 = ["base-court", "bat-fowling", "beef-witted"...
var noun = ["apple-john", "baggage", "barnacle"...
var insult = "Thou art a " + adjective1[Math.floor(Math.random() * 60)] + ", " + adjective2[Math.floor(Math.random() * 60)] + ", " + noun[Math.floor(Math.random() * 60)] + "!";
var genInsult = function() {
x=document.getElementById("replace");
x.innerHTML=insult;
};
</script>
<p id= "replace">Your insult will appear here!</p>
<button type="button" onclick="genInsult()">Generate Insult</button>
However, once you press the button once, you cannot press it again to generate another insult unless you refresh the page.
So my question is: how can I make this button reusable by using JavaScript?
I've tried searching for an answer to my question, but the problem is that I'm so new to JavaScript that I often have trouble understanding other people's questions and the answers to them. Also, a lot of responses reference jQuery, a language I do not know. If anyone has a solution within the realm of JavaScript, I would be extremely grateful!
I might not know a heck of a lot now, but I am very eager to learn!
Move this:
var insult = "Thou art a " + adjective1[Math.floor(Math.random() * 60)] + ", " + adjective2[Math.floor(Math.random() * 60)] + ", " + noun[Math.floor(Math.random() * 60)] + "!";
within your genInsult() function and you should be good. Right now it's outside so it will only generate once.
As has already been stated, your main issue is just that the creation of the insult is outside of your function, so it is only created once, rather than each time the function is called. I really enjoy re-factoring code, I wanted to offer you this: (click here for live demo)
I have written your app using an object oriented pattern and cleaning up a lot of mess and inefficiency. I think it will do you a lot of good to study this and learn all you can!! By the way, don't ever use inline javascript (the click function in your html) unless you're using a framework that makes sense of it (like AngularJS).
<p id="insult">Your insult will appear here!</p>
<button type="button" id="generate">Generate Insult</button>
and the js:
var generator = { //only one global variable!!
init: function() { //this sets up your app for use
var elem = document.getElementById('insult');
var obj = this; //cache reference to the generator object (the "this" pointer will be changed within the click function
var button = document.getElementById('generate');
button.addEventListener('click', function() {
elem.innerText = obj.generateInsult();
});
},
generateInsult: (function() { //use an IIFE to give a nice closure to these variables
var generateInsult = function() {
return "Thou art a "+adjs1[r(adjs1)]+", "+adjs2[r(adjs2)]+", "+nouns[r(nouns)]+"!";
};
function r(arr) {
return Math.floor(Math.random() * arr.length);
}
var adjs1 = ["artless", "bawdy", "beslubbering"];
var adjs2 = ["base-court", "bat-fowling", "beef-witted"];
var nouns = ["apple-john", "baggage", "barnacle"];
return generateInsult;
}())
};
generator.init(); //I suggest running this on document ready to be sure the elements are loaded. If not, this will not work. Keep that in mind!

How to communicate between two NativeWindows in Air

How can I send messages to or manipulate the contents of a NativeWindow instance from the parent window that created it?
I have read several places that to communicate between NativeWindow instances in the same application you need to "maintain a LocalConnection or write a whole whack of JavaScript". As it happens, I have no issue with writing a whole whack of JavaScript, but there doesn't seem to be any documentation on how to do it. Does anyone know what to do?
Thanks for any help you can give me!
Answering my own question here. "A whole whack of JavaScript" can be summed up in one ridiculous line:
var myWindow = air.NativeApplication.nativeApplication.openedWindows[intWindowCount].stage.getChildAt(0).window
myWindow.document.getElementById('status').innerHTML = "success";
This assumes you are using NativeWindow and loading HTML into using HTMLLoader and you're only loading one child. intWindowCount represents the number of opened windows (including the Introspector). 0 represents the number of children you created using the stage.addChild() method. The code I'm using is below in its entirety. There is likely some cleaning up to do, but it should be a good starting point for anyone that needs to do the same thing:
var htmlView = new air.HTMLLoader();
htmlView.width = 300;
htmlView.height = 500;
var objWindowOptions = new air.NativeWindowInitOptions();
objWindowOptions.transparent = false;
objWindowOptions.systemChrome = air.NativeWindowSystemChrome.STANDARD;
objWindowOptions.type= air.NativeWindowType.NORMAL;
var wWindow = new air.NativeWindow(objWindowOptions);
wWindow.x = objScreen.x;
wWindow.y = objScreen.y;
wWindow.width = objScreen.width;
wWindow.height = objScreen.height;
wWindow.activate();
wWindow.stage.align = "TL";
wWindow.stage.displayState = runtime.flash.display.StageDisplayState.FULL_SCREEN_INTERACTIVE;
wWindow.stage.scaleMode = "noScale";
wWindow.stage.addChild( htmlView );
htmlView.load( new air.URLRequest("pageTwo.html") );
setTimeout(function(){
objScreen.setWindowReference(air.NativeApplication.nativeApplication.openedWindows[intWindowCount].stage.getChildAt(0).window);
objScreen.setClock(cClock);
cClock.screen = objScreen;
},500);
The timeout at the end is a horrible, embarrassing hack. I'm only using it because I haven't found the right event yet to use with addEventListener().

Javascript text Resize

Without getting into the "should a text resizer be used or not" debate, I'd like some help with this...suffice to say that my clientele are from and older generation and may be sight impaired...
My script isn't functioning, and I'm not sure why. It's not live yet, so here's what I'm working with:
function fsize(size,unit,id){
var vfontsize = document.getElementById("#colleft");
if(vfontsize){
vfontsize.style.fontSize = size + unit;
}
}
var textsize = 14;
function changetextsize(up){
if(up){
textsize = parseFloat(textsize)+2;
}else{
textsize = parseFloat(textsize)-2;
}
}
I'm using onclick events to trigger the size changes. Thanks for your help!
1) You are not using "id" parameter in fsize()
2) Please post your onclicks... how are you using fsize and changetextsize together? You don't seen to be using "textsize" value anywhere ... Also, what happens when you click?
var vfontsize = document.getElementById("#colleft");
should, most likely, be
var vfontsize = document.getElementById("colleft"); // no hash
it seems to me like remnants from a jquery attempt or similar..
and then, tell us how you are calling these functions you have posted..

Categories

Resources