What technologies should I use to load content into a dynamic div? - javascript

I have an interesting project in mind, and I have a question. You can see the look from my jank design below:
I have a variety of technologies I'm planning on leveraging. To give you an idea:
node.js (for various servers)
WebSockets (for chat client and some content I'd rather not disclose)
canvas (for part of the #content)
Now, with this in mind, I have no problem leveraging technologies that are not supported by most browsers. That's not any concern.
For my question, on the page I have laid out above, the only thing I want to change (besides the updating chat feature) is the content. I would like to load the "Home", "About", "Contact" and "Login" sections of my website into the #content portion of the page.
Now, I have an instinct to say the best way to achieve this goal is through AJAX, but I'm not sure. Since I could possibly just set up some files with the HTML I'd like to display, and then onclick, load them into the #content section.
Is this the best method to use? I'm looking for practicality and performance.
Sorry for the bizarre question.
Thanks!

If you are wanting to load these sections dynamically, ajax is the only way to go. I would definitely check out using a JavaScript library to handle the internals of making ajax calls for you, as writing this part from scratch can be difficult to do in a cross-browser manner. I would highly recommend jQuery for this: http://jquery.com/
I saw you mentioned WebSockets. WebSockets can be good for offloading some intensive JS processing, but it cannot be used for interacting with the DOM (e.g. accessing HTML elements, changing their content, getting form values, etc.).

Alternatively, you can decide not to have to learn AJAX, or deal with external Comet libraries, and use something like NOLOH which takes care of all these plumbing issues for you allowing you to focus on your application. For example, I took the liberty to create an actual NOLOH application based on your mockup design, which automatically uses AJAX for the content, and uses NOLOH's built in Comet support for the chat.
Click here for functioning example: http://www.noloh.com/Demos/StackOverflow1
As you can see from the very basic code (all of the code) posted below, and on github here, you simply lay out your objects, and tell them what you would like to do. NOLOH takes care of the rest, and handles all cross browser issues, client-server issues, and most other things you can imagine.
NOTE: This is only one of many ways to approach it, I could've used different layout types, more concise syntax, class variables instead of locals and external CSS, but I felt a simple approach would make things clearer. Also, sorry for using the unwieldy Yahoo URL as it was the most readily available.
require_once('/NOLOH/NOLOH.php');
class StackOverflowExample extends WebPage
{
function __construct()
{
parent::WebPage('StackOverflow 5672167');
$nav = new Panel(0, 0, 600, 30);
$chat = new Panel(0, $nav->Bottom, 200, 500);
$content = new MarkupRegion('', $chat->Right, $chat->Top, 400, 350);
$rooms = new Panel($content->Left, $content->Bottom, 400, 150);
$footer = new Panel(0, $chat->Bottom, 600, 50);
$chat->BackColor = Color::LightGreen;
$content->BackColor = Color::Yellow;
$rooms->BackColor = Color::Orange;
$footer->BackColor = Color::Gray;
$this->Controls->AddRange($nav, $chat, $content, $rooms, $footer);
$sections = array('HOME', 'ABOUT', 'CONTACT', 'LOGIN');
foreach($sections as $section)
$nav->Controls->Add(new Link(null, $section, 0, 5))
->Click = new ServerEvent($this, 'LoadSection', $content, $section);
$nav->Controls->AllCSSMarginRight = '5px';
$nav->Controls->AllLayout = Layout::Relative;
$nav->CSSTextAlign = 'right';
//Comet (Listener), Bind to Yahoo Flickr API through YQL
$this->Controls->Add($listener = new Listener(
'http://query.yahooapis.com/v1/public/yql?q=select%20source%20from%20flickr.photos.sizes%20WHERE%20photo_id%20in%20(select%20id%20from%20flickr.photos.recent)%20and%20label%3D%22Thumbnail%22',
new ServerEvent($this, 'LoadImage', $chat)));
//Default Section
$this->LoadSection($content, URL::GetToken('section', 'HOME'));
}
function LoadSection($contentPanel, $section)
{
$section = strtolower($section);
if(file_exists($file = 'Content/' . $section))
{
$contentPanel->Text = file_get_contents($file);
URL::SetToken('section', $section);
}
}
function LoadImage($chat)
{
foreach(simplexml_load_string(Listener::$Data)->results->size as $photo)
{
$url = $photo['source'];
$chat->Controls->Add($image = new Image((string)$url, rand(0, $chat->Width), rand(0, 200), 100, 100));
Animate::Top($image, $chat->Height - $image->Height, 3000);
Animate::Opacity($image, Animate::Oblivion, 3000);
}
}
}
Alternatively, you can use the NOLOH NavHandler Nodule, so that your content is bookmarkable without you having to worry about implementing the very basic NOLOH Token functions, which I took the liberty to add here (URL::GetToken), so that the app is bookmarkable.
You're free to sign-up for a free NOLOH sandbox, and copy the code into your sandbox and play around with it. One way would be to change the MarkupRegion to an EditRegion so you have automatic edit-in-place capabilities.
Disclaimer: I'm a co-founder of NOLOH

Related

My JSLink script will not work

I am attempting to use JSLink ..finally.. and I am having some trouble that I cannot seem to straighten out. For my first venture down the rabbit hole I chose something super simple for use as proof of concept. So I looked up a tutorial and came up with a simple script to draw a box around the Title field of each entry and style the text. I cannot get this to work. Is there any chance you can take a look at this code for me? I used the following tokens in the JSLink box.
~sitecollection/site/folder/folder/file.js
And
~site/folder/folder/file.js
The .js file is stored on the same site as the List View WebPart I am attempting to modify. The list only has the default “Title” column.
(function () {
var overrideContext = {};
overrideContext.Templates = {};
overrideContext.Templates.Item = overrideTemplate;
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideContext);
}) ();
function overrideTemplate(ctx) {
return “<div style=’font-size:40px;border:solid 3px black;margin-bottom:6px;padding:4px;width:200px;’>” + ctx.CurrentItem.Title + “</div>”;
}
It looks as though you are attempting to override the context (ctx) item itself, where you actually just want to override the list field and the list view in which the field is displayed. Make sense?
Firstly, change overrideContext.Templates.Item to overrideContext.Templates.Fields :
(function () {
var overrideContext = {};
overrideContext.Templates = {};
overrideContext.Templates.Fields = {
// Add field and point it to your rendering function
"Title": { "View": overrideTemplate },
};
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideContext);
}) ();
Then when the JSLink runs the renderer looks for the Title field in the List view, and applies your overrideTemplate function.
function overrideTemplate(ctx) {
return “<div style=’font-size:40px;border:solid 3px black;margin-bottom:6px;padding:4px;width:200px;’>” + ctx.CurrentItem.Title + “</div>”;
}
In terms of running multiple JSLinks on a SharePoint page, it is quite possible to run multiple JSLink scripts, they just need to be separated by the pipe '|' symbol. I use SharePoint Online a lot and I see the following formatting working all the time (sorry Sascha!).
~site/yourassetfolder/yourfilename.js | ~site/yourassetfolder/anotherfilename.js
You can run as many scripts concurrently as you want, just keep separating them with the pipe. I've seen this on prem also, however you might want to swap out '~sites' for '~sitecollection' and make sure the js files you are accessing are at the top level site in the site collection if you do so!
I have noticed when running multiple JSLinks on a list or page because they are all doing Client Side Rendering, too many will slow your page down. If this happens, you might want to consider combining them into one JSLink script so that the server only has to call one file to return to the client to do all the rendering needed for your list.
Hope this helps.

How to trigger a JavaScript function using the URL

I really didn't know how to explain my question in the title, so I tried.
Anyways, this is my problem. I have a webpage which is basically a puzzle. The basic premise of it is that when you visit a certain link, it will trigger a function and show the next piece.
Here's one of the functions that will show the piece -
function showone() {
var elem = document.getElementById("one");
if (elem.className = "hide") {
elem.className = "show"
}
}
The reason that it's built like this, is because the pieces are constructed and placed using an HTML table, using classes to hide and show them.
What I need to do, is somehow create a URL that will trigger a new piece. For example, "www.website.com/index.html?showone" is what I'd like. This would trigger the "showone" function.
I don't know how to do this though, and after a fair bit of searching, I'm more confused than I was to begin with.
The reason I'm using JavaScript to begin with, is that the page can't refresh. I understand that this might not be possible, in which case, I'm open to any suggestions on how I could get this to work.
Thanks in advance, any suggestions would be greatly appreciated.
-Mitchyl
Javascript web application frameworks can to this for you, they allow to build web application without refresh page.
For example you can use backbonejs it has Router class inside and it very easy to use.
code is easy as :
var Workspace = Backbone.Router.extend({
routes: {
"help": "help", // #help
"search/:query": "search", // #search/kiwis
"search/:query/p:page": "search" // #search/kiwis/p7
},
help: function() {
...
},
search: function(query, page) {
...
}
});
is also you can use angularjs it is big one that supports by Google.
Maybe this solution can help you?
$("a.icon-loading-link").click(function(e){
var link = $(e.target).prop("href"); //save link of current <a> into variable
/* Creating new icon-tag, for example $("<img/>", {src: "link/to/file"}).appendTo("next/dt"); */
e.preventDefault(); //Cancel opening link
return false; //For WebKit browsers
});

How to use the getLogo function of the Spil API

How would I use the getLogo function to display the Spil Logo on inside my HTML5 game?
Here's the link to their docs
http://developers.spilgames.com/wiki/Developer_Platform_-_Learning_center_-_HTML5_API_getLogo
I don't understand if it's meant to display their logo automatically, or if I'm meant to do something with the object data it returns, and if so how would use it?
We provide basically only two properties: a URL to the image and a function. What you need to do within your game is attach the Javascript link to the image.
A typical logo implementation looks like this for a DOM implementation. But of course this depends on the nature of your game and if you're using a framework:
GameAPI.loadAPI(function (apiInstance) {
// getLogo example
var logoData = apiInstance.Branding.getLogo();
// Create a DOM element and use the values returned by the call
var logo = document.createElement('img');
logo.src = logoData.image;
logo.addEventListener('click', logoData.action);
document.body.appendChild(logo);
});
You can find a tutorial complete with jsFiddle example here: http://developers.spilgames.com/wiki/Developer_Platform_-_Learning_center_-_HTML5_API_-_(Tutorial)_Get_logo
If you run into technical issues, you can always get in touch with the Tech Support team using the "Support" tab on this page: http://developers.spilgames.com/contact
Hopefully this answers your question!

Using Piwik for a Single Page Application

Building a single page / fat client application and I'm wondering what the best practice is for including and tracking using http://piwik.org/
I'd like to use Piwik in a way that is architecturally sound and replacable with a different library in the future.
It seems that there are two basic options for tracking with Piwik:
Fill up a global _paq array with commands, then load the script (it's unclear to me how to record future "page" views or change variables though)
Get and use var myTracker = Piwik.getTracker()
_paq approach:
myApp.loadAnalytics = function() { /* dynamically insert piwik.php script */ }
myApp.track = function(pageName) {
window._paq = window._paq || [];
_paq.push(['setDocumentTitle', pageName]);
_paq.push(["trackPageView"]);
}
myApp.loadAnalytics()
// Then, anywhere in the application, and as many times as I want (I hope :)
myApp.track('reports/eastWing') // Track a "page" change, lightbox event, or anything else
.getTracker() approach:
myApp.loadAnalytics = function() { /* dynamically insert piwik.php script */ }
myApp.track = function(pageName) {
myApp.tracker = myApp.tracker || Piwik.getTracker('https://mysite.com', 1);
myApp.tracker.trackPageView(pageName);
}
myApp.loadAnalytics()
// Then, anywhere in the application, and as many times as I want (I hope :)
myApp.track('reports/eastWing') // Track a "page" change, lightbox event, or anything else
Are these approaches functionally identical? Is one preferred over another for a single page app?
To have the tracking library used (eg. piwik) completely independent from your application, you would need to write a small class that will proxy the functions to the Piwik tracker. Later if you change from Piwik to XYZ you can simply update this proxy class rather than updating multiple files that do some tracking.
The Async code is a must for your app (for example a call to any 'track*' method will send the request)
The full solution using .getTracker looks like this:
https://gist.github.com/SimplGy/5349360
Still not sure if it would be better to use the _paq array instead.

Creating a custom echo node with web-audio

I'm playing with the webkit Audio API and I'm trying to create an Echo effect, to accomplish that I've connected a DelayNode with a GainNode in a loop (The output of one is the input of the other, and viceversa).
The effect works fine, but now I want to create an EchoNode Object that I can just plug-in and connect with the other AudioNode objects.
Something like:
myEchoNode = new EchoNode();
myConvolverNode = context.createConvolver();
myConvolverNode.connect(myEchoNode);
I think that I should make my EchoNode inherit from AudioNode, so that the connect function of every other AudioNode would work, but I don't know how to do that in Javascript with the web Audio API.
Can anyone give me a hint, or if you think that there is a better way to accomplish that I would greatly appreciate it.
Thanks
Oskar's solution should do the trick, but I want to point out that it will require you to connect to your EchoNode in a nonstandard way (using EchoNode.input rather than simply connecting to the EchoNode itself). For simple effects such as feedback delay, this can be avoided by creating the EchoNode via a factory function that returns a native DelayNode mixed with some extra properties. Here's an example from SynthJS:
function FeedbackDelayNode(context, delay, feedback){
this.delayTime.value = delay;
this.gainNode = context.createGainNode();
this.gainNode.gain.value = feedback;
this.connect(this.gainNode);
this.gainNode.connect(this);
}
function FeedbackDelayFactory(context, delayTime, feedback){
var delay = context.createDelayNode(delayTime + 1);
FeedbackDelayNode.call(delay, context, delayTime, feedback);
return delay;
}
AudioContext.prototype.createFeedbackDelay = function(delay, feedback){
return FeedbackDelayFactory(this, delay, feedback);
};
As you can see, the result is a native DelayNode that can be connected to other nodes in the standard fashion, but it has an attached gain node that provides the feedback effect.
Have a look at this article I wrote, it might give you some ideas: http://www.html5rocks.com/en/tutorials/casestudies/jamwithchrome-audio/ (which explains the basic idea behind tuna.js that Taoist recommended).

Categories