I have java script file that reads in a csv file, and has many functions to to visualize the data differently, using d3. I want each visualization to be displayed in different html pages. Ive made every html page, refer to the javascript file. Each page also has its own script that calls functions from the referred javascript file.
The problem, I am facing is that when ever I go to a new page, the function gets called before the data being read. Only works when refreshing the page. I there a way to just read the data in once, and every page can access it.
If you look at the code below, callingFunction() returns undefined (maybe because data is not stored in var data?) The callingFunction() works fine when the page is refreshed.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>D3</title>
**<script src="my.js"></script>** //my script file
</head>
<body>
<script>
callFunction(); //uses var data defined in my.js
</script>
Here is the "my.js":
var data;
function data(file){d3.csv("file", function (error, data) {
ds = data;
callFunction();
}
load your script after the target DOM :
<canvas></canvas>
...........................
<script type="text/javascript"></script>
Use angularJs Js library: it organize your js code according to MVC design pattern.
If you have more than one method to implement a business logic , Use console.time & console.timeEnd to evaluate code performance .
console.time('anID');
// Here your code
console.timeEnd('anID');
Related
I am trying to call the Math.matrix() function, and I am quite certain I am not importing the file correctly into my javascript code. I have read through the StackOverflow question "how to include and use math.js": and given that advice, I have the following :
<HTML >
<!DOCTYPE html>
<head>
<script src=https://cdnjs.cloudflare.com/ajax/libs/mathjs/5.1.1/math.js>
</script>
<script type="text/javascript" >
function rotate_clockwise(){
/* code skipped */
matrix = Math.matrix(matrix, rotationmatrix);
}
</script>
</head>
<body>
</body>
</HTML>
where the cdns reference I have taken from this link
But on run when rotate_clockwise is called via slider the chrome 68 debugger states Uncaught type error : Math.matrix is not a function, so I do believe I am not including this file correctly.
My base assumption is that including a file once, in one set of script tags, is enough for any javascript function to use this library, which resides within a different set of script tags.
Thanks so much for any assistance you can provide.
I think you need math.matrix(...)--lower case math since Math is a standard JS library.
Here is my code:
<!DOCTYPE html>
<html lang="en" >
<head>
<script type="text/javascript">
function showResponse(response){
var responseString = JSON.stringify(response, '', 2);
document.getElementById('response').innerHTML += responseString;
}
function onClientLoad(){
gapi.client.load('youtube','v3', onYouTubeApiLoad);
}
function onYouTubeApiLoad(){
gapi.client.setApiKey('MyActualKey');
search();
}
function search(){
var request = gapi.client.youtube.search.list({
part: 'snippet'
});
request.execute(onSearchResponse);
}
function onSearchResponse(response){
showResponse(response);
}
</script>
<title></title>
<script src="https://apis.google.com/js/client.js?onload=onClientLoad"></script>
</head>
<body>
<div id="response"></div>
</body>
</html>
This code is from Codecademy, and I thought I can use it on an html page and it would work.
I got an API key from google and I set my Youtube data api v3 setting to enabled in my google developers console, but this code gives me a blank page.
What am I doing wrong?
There are a few missing pieces, code snippets which codecademy likely took for granted but which are essential when placing it in your own server outside of their app. First of all, you need a line that actually loads the gapi library from google. You can put this in your code, just before the closing :
<script src="https://apis.google.com/js/client.js?onload=onClientLoad"></script>
In short, this will get the library from Google's servers, and when it's loaded the library will automatically call your onClientLoad method, kicking off your app.
Next, you say you have an API key; make sure you put that key into your code by replacing this:
gapi.client.setApiKey('MyKey');
with this:
gapi.client.setApiKey('{WHATEVER_YOUR_ACTUAL_KEY IS');
Finally, as the commenters mentioned, your body is empty, so when your code executes the showResponse method there's no place to put what comes back. Add this:
<div id="response"></div>
I'm writing a static web site that uses JQuery to make some AJAX calls to a RESTful API and populate the page with data.
The site functions correctly (and quickly), everything is good.
As I extend the site and add additional pages, I'm noticing that I'm duplicating certain regions on every page.
For instance, each page shares a common header element.
<header>...Some non-trivial content...</header>
Rather than repeat this definition on each page is there some mechanism, by which, I can define this section once and include it in each document.
Remember that the pages must be served statically but any standard complaint browser functionality can be utilised.
Is there a good way to do this, and what is it or, will I have to abandon DRY principles for this aspect of my client side code?
There's definitely some ways to achieve this. You could either do it using some features of your server-side language that allows to include the content of a page in another page, or if you do not have any server-side technology, you could simply put that code in it's own html document and load it's content using AJAX.
In jQuery it could look like:
$('#header').load('header.html');
However, if the content isin't static for all pages, you could always define a JS module that would be responsible to render this header. You module could make use of a client-side templating engine, like Mustache, Handlebars, etc. However you do not have to use any of these.
Here's a simple example:
DEMO
//in somefile.js, please note that you should namespace your modules
var Header = {
//default config
config: {
el: '#header',
title: 'Some title'
},
init: function (config) {
var cfg = this.config = $.extend({}, this.config, config);
$(cfg.el).html('<h1>' + cfg.title + '</h1>');
}
};
$(function () {
Object.create(Header).init({
title: 'Some other title'
});
Object.create(Header).init({
el: '#header1',
title: 'Yeah'
});
});
As I mentioned in the comment, this is how I do it:
main.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Main page</title>
<sript src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(function(){
$('#commonsection').load('reusablefile.htm');
// which is eqvivalent to:
//
// $.ajax({
// url: 'reusablefile.htm',
// dataType: 'html',
// success: function(data){
// $('#commonsection').html(data);
// }
// });
});
</script>
</head>
<body>
<div id="commonsection"></div>
</body>
</html>
reusablefile.html:
<script>
(function($){ //separate scope to keep everything "private" for each module
//do additional javascript if required
})(jQuery);
</script>
<p>...Some non-trivial content...</p>
You could use jQuery's ajax as to load the header file. In each file you could load the html like so:
$('#header').load('header.html');
Since you're already using AJAX calls to populate your site with data, you could do the same for the common regions.
Just store the HTML for those regions in a separate file and load it in the page with AJAX. Also, you can work with caching using the Cache-Control headers on that file so you don't reload the entire content from the server with each page load.
If you're using straight HTML, you could do it with a SSI include command or by creating a template page and including it in jQuery. Both of these links might help you
Include another HTML file in a HTML file
and
http://www.htmlgoodies.com/beyond/webmaster/article.php/3473341/SSI-The-Include-Command.htm
It looks like this in modest:
main.xhtml
<?xml version='1.0' encoding='UTF-8'?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<include>reusablePiece</include>
</head>
<body>
<reusablePiece/>
</body>
</html>
reusablePiece.xml
<header>...Some non-trivial content...</header>
Very simple would be the jQuery .clone() function.
If you have more complex content I recommend looking at Handlebars.js which is a full fledged JS templating engine.
I am developing a simple pyramid application where I am using JQuery to do AJAX requests. I have until now had my javascript code within my chameleon templates. Now I want to extract my javascript into another location (e.g. as static resources).
My problem is that I find my javascript code relies on dynamically generated content like so:
$.post("${request.route_url('my_view')}",{'data': 'some data'}, function(html){
$("#destination").html(html);
});
The dynamic element being:
"${request.route_url('my_view')}"
Which is calling the route_url method of the request object within the template.
Is there a recognised pattern for separating such javascript files into their own templates and providing routes and views for them or do I simply keep my javascript in my page template?
Yes; you generally put context-specific information like expanded routes into the templates and access this information from your (static) JavaScript libraries.
Including the context info can be done in various ways, depending on taste:
You could use a data attribute on a tag in your generated HTML:
<body data-viewurl="http://www.example.com/route/to/view">
...
</body>
which you then, in your static JS code load with the jQuery .data() function:
var viewurl = $('body').data('viewurl');
Use a made-up LINK tag relationship to include links in the document head:
<head>
<link rel="ajax-datasource" id="viewurl"
href="http://www.example.com/route/to/view" />
...
</head>
which can be retrieved using $('link#viewurl').attr('href'), or $('link[rel=ajax-datasource]').attr('href'). This only really works for URL information.
Generate JS variables straight in your template, to be referenced from your static code:
<head>
...
<script type="text/javascript">
window.contextVariables = {
viewurl = "http://www.example.com/route/to/view",
...
};
</script>
</head>
and these variables are referable directly with contextVariables.viewurl.
I'm building a webpage and I want to re-use some HTML I have elsewhere on my website. The page I am building (index.html) can dynamically get and insert the HTML I want (existing.html) using XMLHttpRequest. However, the HTML I want to get is populated by some Javscript. That Javascript is not being executed when I load it into my new page:
index.html:
<html>
<head>
<script type = "text/javascript">
... //use XMLHttpRequest to load existing.html
initExistingHTML(); //this is function which populates loaded HTML, is not executed
</script>
</head>
<html>
existing.html:
<div>
<script type = "text/javascript">
function initExistingHTML() {
... // do some stuff
}
</script>
</div>
How can I load existing.html and run the script which populates it?
Once the page has loaded, add in existing.html via innerHTML. Rather than calling its functions, just let existing.html's code execute, which will do the same as if it were in the onload section.
EDIT: Or, you could just correct that typo you have. initExistingHTML != initExistingHtml.
lol