After getting my AJAX to work with help from another question I asked, I'd like to create another file that contains my functions to keep my code clean. I haven't found anything useful online, so I am thinking it might not be possible. Here is the code I'd like to extract:
<script> <!-- overall co2 -->
var co2;
var url="/solarpv/api/co2/list"
var jsonObject;
$(document).ready(function(){
$.getJSON(url,function(result){
jsonObject = result;
co2 = result[0].Cumulative_CO2;
$('#ajaxRequest').html("Our solar panels have saved " + co2 + " pounds of CO2 since they were installed.");
});
});
<!-- today co2 -->
var co2today;
var url2="/solarpv/api/co2/today"
$(document).ready(function(){
$.getJSON(url2,function(result){
co2today = result[0].CO2;
$('#today').html("Our Solar Panels have saved " + co2today + " pounds of c02 so far today.");
});
});
<!-- yesterday's CO2 -->
var url3 = "/solarpv/api/co2/list?start=2013-04-28%2001:00:00&end=2013-04-29%2001:00:00";
var yesterdayCO2;
$(document).ready(function(){
$.getJSON(url3,function(result){
yesterdayCO2 = result[0].Cumulative_CO2;
$('#yesterday').html("Yesterday alone, our solar panels saved the same amount of CO2 it would take " + yesterdayCO2/1.98 + " people to create!");
});
});
<!-- last years's CO2 -->
var url4 = "/solarpv/api/co2/list?start=2012-04-28%2001:00:00&end=2013-04-29%2001:00:00";
var trees;
$(document).ready(function(){
$.getJSON(url4,function(result){
trees = result[0].Cumulative_CO2;
$('#yesterday').html("Last year our solar panels saved the equivalent of " + trees/48.061 + " trees worth of C02");
});
});
</script>
An example of the html that would be left in the file that uses this looks like:
<li id="yesterday">
<script>
document.write("Yesterday alone, our solar panels saved the same amount of CO2 it would take " + yesterdayCO2 + " people to create!");
</script>
</li>
Use this tag to load the javascript. Put it at the bottom of your HTML just before </html>
<script type="text/javascript" src="myJs.js"></script>
Then you have to put the javascript (without the <script> tags) in the file named myJs.js and make it loadable from the browser.
Related
There are several similar questions, so I hope this is a unique problem. None of the proposed solutions on those similar questions have solved my issue. Humble apologies from this beginner if I messed up somehow.
I have an empty div on my page with I am loading using javascript with strings from an array. Currently, I have a script running on a button which reloads the entire page. I would like for that button to just reload the div with items from my javascript array.
Here is my code:
<html>
<head>
<link rel="stylesheet" href="obliqueStyle.css">
<style></style>
</head>
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<body>
<div id="wrapper">
<div id="strategyBox"></div>
<div id="button">
<a class="againbutton" onclick="buttonReload()">Again</a>
<script>
var buttonReload = function() {
document.getElementById("strategyBox").innerHTML = '<p id="strategyText">' + randomStrategy + '</p>';
}
</script>
</div>
</div>
<script src="os.js"></script>
</body>
Here is a snippet of my array and the JS (coming from the os.js file referenced in index.html) I am using to load the div initially/on refresh:
var obliqueStrategy = ["Abandon normal instruments",
"Accept advice",
"Accretion",
"A line has two sides"];
var randomStrategy = obliqueStrategy[Math.floor(Math.random() * obliqueStrategy.length)];
document.getElementById("strategyBox").innerHTML = '<p id="strategyText">' + randomStrategy + '</p>';
I've tried calling the same javascript as a function in script in the html like this:
<div id="button">
<a class="againbutton" onclick="buttonReload()">Again</a>
<script>
var buttonReload = function() {
document.getElementById("strategyBox").innerHTML = '<p id="strategyText">' + randomStrategy + '</p>';
}
</script>
</div>
I've tried using the jQuery AJAX load function like this:
<script>
$(function() {
$("#againbutton").on("click", function() {
$("#strategyBox").load("index.html")
return false;
})
})
</script>
I've played around with variations of the above and tried a couple other things that I'm forgetting exactly how and what I did, so I can't include them. I've really hit a wall on this even though it seems profoundly simple.
Thanks in advance for any help.
Here's one method: http://jsfiddle.net/kxqcws07/
HTML
<div id="wrapper">
<div id="strategyBox"><p id="strategyText"></p></div>
<div>
<input type="button" class="againbutton" value="Again">
</div>
</div>
Javascript
//wrapping your logic in a namespace helps reduce the chances of naming collisions of functions and variables between different imported js files
var localNameSpace = function() {
//private array containing our strings to randomly select
var obliqueStrategy = [
"Abandon normal instruments"
, "Accept advice"
, "Accretion"
, "A line has two sides"
];
var api = {
//bindButtonAction binds the generateRandomStrategy function to the click event of the againbutton
bindButtonAction: function() {
$('#wrapper .againbutton').click(api.generateRandomStrategy);
}
, generateRandomStrategy: function() {
//get the position of one of the string randomly
//Math.random() returns a float value < 1 so multiplying it by 100 gets us a range of (0.* - 99.*)
//then we Math.floor() that to get rid of the float value and keep just the integer part
//finally we modulus it with the length of the string array
//if you are unfamiliar with modulus, what it does is gives you the remainder of a division. for instance 10 / 3 gives you 3 with a remainder of 1, so 10 % 3 would be just 1.
//what this does for us is keeps the random offset of our within the bounds of the array length (0 to length -1)
var randomOffset = Math.floor(Math.random() * 100) % obliqueStrategy.length;
//finally once we have the offset, we set the html to the string at the position in the array
$('#wrapper #strategyBox #strategyText').html( obliqueStrategy[randomOffset] );
}
};
return api;
}();
$(document).ready(function() {
//here we call the bind action so the button will work, but we also explicitly call the generateRandomStrategy function so the page will preload with a random string at the start
localNameSpace.bindButtonAction();
localNameSpace.generateRandomStrategy();
});
I'm having some trouble running some JS inside a html5 body.
Here's what's happening, whenever I remove all instances of the arrays from the JS file I am using, the script loads fine in the index file, however, when I add src to the attribute and/or mention an array name from said file, it breaks. simple as that.
since I'm planning on making a pretty big site, I have already begun organizing my root.
here's a little demo:
rootFolder/
index.htm
js/targetJS.js
here's the code
<script src="js/targetJS.js" type="text/javascript">
document.writeln("<table id='services' class='services' name='services'>");
document.writeln("<tr>");
document.writeln("<th> Preview: </th>");
document.writeln("<th> Description: </th>");
document.writeln("<th> Cost: </th>");
document.writeln("</tr>");
var i = 0;
//for ( i = 0; i < servicePrev.length; i++)
{
if (i % 2 == 0){
document.writeln("<tr class='even' id='even'>");
}
else{
document.writeln("<tr class='odd' id='odd'>");
}
//document.writeln("<td> " + servicePrev[i] + " </td>");
//document.writeln("<td> " + serviceDesc[i] + " </td>");
//document.writeln("<td> " + serviceCost[i] + " </td>");
document.writeln("</tr>");
}
document.writeln("</table>");
</script>
Whenever i add the src in the attribute and the lines that are commented out, the code does not work, however, when I omit the src and the lines that are currently commented out, the code works fine. even JSfiddle reports it working fine.
The contents of the JS file are 3 arrays with 5 indexes.
You need to seperate your tags
<script type="text/javascript" src="awesomescript.js"></script>
and
<script>
// some awesome code here
</script>
Since html5, you are free to name <script type="text/javascript"> or just use <script> for javascript, as text/javascript is default.
Quoted from http://javascript.crockford.com/script.html
The script tag has two purposes:
It identifies a block of script in the page. It loads a script file.
Which it does depends on the presence of the src attribute. A
close tag is required in either case.
The src attribute is optional. If it is present, then its value is a
url which identifies a .js file. The loading and processing of the
page pauses while the browser fetches, compiles, and executes the
file. The content between the and the
should be blank.
So, the script file should be loaded by dedicated script tag without content, the script content should be inserted into another script tag, after all if you have other errors you can check in the console of your broswer
<script src="js/targetJS.js" type="text/javascript"></script>
<script type="text/javascript">
document.writeln("<table id='services' class='services' name='services'>");
document.writeln("<tr>");
document.writeln("<th> Preview: </th>");
document.writeln("<th> Description: </th>");
document.writeln("<th> Cost: </th>");
document.writeln("</tr>");
var i = 0;
//for ( i = 0; i < servicePrev.length; i++)
{
if (i % 2 == 0){
document.writeln("<tr class='even' id='even'>");
}
else{
document.writeln("<tr class='odd' id='odd'>");
}
//document.writeln("<td> " + servicePrev[i] + " </td>");
//document.writeln("<td> " + serviceDesc[i] + " </td>");
//document.writeln("<td> " + serviceCost[i] + " </td>");
document.writeln("</tr>");
}
document.writeln("</table>");
</script>
I am using nexusUI for a project and would like to use templates but discovered that don't seem to be rendered. I suppose it is because of the missing canvas context but I am not quite sure how to go about it... Any pointers?
Here's the code that illustrates the issue:
<!-- This renders fine, as expected -->
<div> <canvas nx='button'></canvas> </div>
<!-- this is my rendering container -->
<div class="nxContainer"></div>
<!-- and a template that should contain a "dial" widget -->
<script type="text/html" id="test">
<div data-content="widget"> </div>
</script>
<!-- counter example to make sure that loadTemplate is actually working -->
<div class="Container"></div>
<script type="text/html" id="test2">
<div data-content="text"> </div>
</script>
$(function () {
var nxus = {
widget: "<canvas nx='dial'></canvas>",
text: "Boo!"
}
$(".nxContainer").loadTemplate("#test", nxus);
$(".Container").loadTemplate("#test2", nxus);
});
http://jsfiddle.net/745vhffb/4/
edit:
So after poking around some more and looking through the source code of the nexusUI library, it looks like I found a solution and I updated my fiddle, which is now at revision #9 (I exceeded my quota for posting links).
nx.elemTypeArr.push("myslide");
var mySlider = "myslide";
var x = new slider('myslide');
x.init();
So basically, it looks like I have to take care of registering the new widget with nx and instantiating it.
So here's a complete solution to my issue:
function instantiateWidget(container, template, widgetType, id, destination){
var sub = {
widget: "<canvas nx='" + widgetType + "' id='" + id + "'></canvas>"
}
$(container).loadTemplate(template, sub);
nx.elemTypeArr.push(id);
eval(id + " = new " + widgetType + "('" + id + "', " + destination + ");");
eval(id + ".init();");
}
and then
instantiateWidget("#nxContainer", "#test", "dial", "local");
and this will populate the container with the template:
<div id="nxContainer"></div>
<script type="text/html" id="test">
<div data-content-append="widget"> </div>
</script>
The nx widgets need to be instantiated in order to obtain their canvas context and only then they become available. There is probably a more elegant way of doing this but for now it will do for me.
I have a product list that is generated by asp
I have product description for each product in a html file
each html file is named: <product.id>.html<br/>
html file size is only 1-3 kb
Within the html file is <title> and <meta name="description" content="..." />
I want to access these in an efficient way so that I can output this as e.g.:
document.write(<product.id>.html.title);<br/>
document.write(<product.id>.html.description);
I have a working solution for the individual product, where I use the description file - but hope to find a more efficient / simple approach. Preferably, I want to avoid having 30+ hidden iframes - google might think that I am trying to tamper with search result and blacklist my page...
Current code:
<iframe src="myfile.html" id="product" style="display:none"> </iframe>
<script type="text/javascript">
document.getElementById('product').onload = function(){
var d = window.frames[frame].document;
var title = d.title : ' ';
var keywords = d.getElementsByName('keywords')[0].getAttribute('content', 0) : ' ';
var descript = d.getElementsByName('description')[0].getAttribute('content', 0) : ' ';
}
</script>
As mentioned here on another Stack Overflow question, you could use:
document.title = "This is the new page title.";
and looking here gives us :
document.getElementsByTagName('meta').content = "New content here";
or:
document.getElementsByTagName('meta').name = "NewName";
With these, you should be able to read and write your tags as needed, I've only used a few examples here, there's surely more.
You could load your files with AJAX. For example (using jQuery):
$.get('myfile.html', function(data){
var title = $(data).find('head title').text();
var keywords = $(data).find('head meta[name="keywords"]').attr('content');
var descript = $(data).find('head meta[name="description"]').attr('content');
});
Here you find the jQuery documentation about using jQuery.get
Found this solution:
<script>
var xhr = $.ajax({
type: "GET",
url: "/files/billeder/ecom/beskrivelser/<!--#Ecom:Group.Number-->.html",
success: function(msg){
msg = msg.split('content="')[1];
msg = msg.split('"')[0];
document.getElementById("a_<!--#Ecom:Group.Number-->").innerHTML = "<p>" + msg + "</p>";
Not yet very elegant... but it works...
I'm trying to reload a JSON file every 10 seconds with JQUERY.
The page is here: http://moemonty.com/chirp/chirp.html
The Code is here:
<html>
<head>
<title>the title</title>
<!-- included Jquery Library -->
<script type="text/javascript" src="./js/jquery-1.4.2.js"></script>
<!-- jquery library -->
</head>
<body>
<script>
$.ajaxSetup({ cache: false }); //disallows cachinge, so information should be new
function loadChirp(){ //start function
var url = "http://www.chirpradio.org/json";
$.getJSON("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22"+url+"%22&format=json&callback=?",
function(data){
console.log(data.query.results.json);
document.write('The artist is: ' + data.query.results.json.artist + '<br/><br/>');
document.write('The artist is: ' + data.query.results.json["record-label"] + '<br/><br/>' );
document.write('The album is: ' + data.query.results.json.album + '<br/><br/>');
document.write('The record label is: ' + data.query.results.json["record-label"] + '<br/><br/>');
document.write('The feedback link is: ' + data.query.results.json["feedback-link"] + '<br/><br/>');
document.write('The database id is: ' + data.query.results.json["database-id"] + '<br/><br/>');
document.write('The time is: ' + data.query.results.json.timestamp.time + ' ');
document.write(data.query.results.json.timestamp["am-pm"] + '<br/><br/>');
document.write('The current dj is: ' + data.query.results.json["current-dj"] + '<br/><br/>');
setTimeout("loadChirp()",5000);
alert('The timeout was triggered.');
});
} //end function
$(document).ready(function(){
//DOCUMENT READY FUNCTION
loadChirp();
});
//DOCUMENT READY FUNCTION
</script>
</body>
</html>
It doesn't seem to be working.
You probably want the previous set of returned data replaced by the new set, instead of appending it. In that case, using jQuery you can do:
<div id='content'></div>
<script>
function loadChirp(){
$.getJSON("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22"+url+"%22&format=json&callback=?",
function(data) {
$('#content').html('The artist is: ' + data.query.results.json.artist + '<br/><br/>');
});
setTimeout("loadChirp()",5000);
}
</script>
etc...
I would expect the loop to work as quoted, but there could be a subtlety around the fact you're using JSONP. I would change the setTimeout call to:
setTimeout(loadChirp, 5000);
...for a couple of reasons. First off, using the function reference rather than a code string is a better idea generally, and second off, you're quite certain that you're getting the right function reference (whereas with the string, what reference you get depends on the context in which the code is executed).
But as Pointy pointed out in a comment, there's a separate issue: document.write will not do what you probably want it to do there. You can only use document.write to write to the HTML stream that's being parsed as part of the original page load. After the page load, you can't use it anymore. Consider using jQuery's append or appendTo and similar functions to add to the DOM after page load.
You have an error in console.log(data.query.results.json); - console is not defined.
Also, you can use setInterval( "function()", 5000 );.
You should definitely use:
setInterval("loadChirp", 10000):
Don't write loadCrirp() inside setInterval as we're only passing a refrence