Printing repeated watermark background image inside an html table - printing

I have a web page that contains a repeated background image, but when i try to print the page using ctrl + p its showing page print preview without background.
Could you please tell me how to force to print the background?
Here's a fiddle: http://jsfiddle.net/qzw639e4/5/
the system has more than one language, therefore, it's necessary to create the image dynamically. It's the reason that I am using a html canvas for this.
function AppViewModel() {
var self = this;
self.items = ko.observableArray([]);
for(var i = 0; i< 10; i++){
var item ={
id: i,
description: 'test'+i,
cost: i*5,
price: i*8,
PriceToCustomer: i*10
}
self.items.push(item);
}
self.print = function(){
window.print();
}
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
canvas.width = "500";
canvas.height = "400";
ctx.font = '15pt Arial';
ctx.save();
ctx.translate(100, 400);
ctx.rotate(-45 * Math.PI / 180);
ctx.fillStyle = "red";
ctx.globalAlpha = 0.3;
var rText = "This text must be a repeated background image.";
ctx.fillText(rText, 0, 0);
ctx.restore();
$('tbody').css('background-image', 'url(' + ctx.canvas.toDataURL() + ') ');
}
ko.applyBindings(new AppViewModel());

I tested the solution below and the bg was correctly printed by the browser:
<body>
<div id="background">
<p id="bg-text"> Sample Background</p>
</div>
<div id="content">
Content of the page goes here.....................
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<p>HI TO EVERBODY </p>
</div>
#background{
position:absolute;
z-index:0;
background:white;
display:block;
min-height:50%;
min-width:50%;
color:yellow;
}
#content{
position:absolute;
z-index:1;
}
#bg-text
{ margin: -900px;
color:lightgrey;
font-size:60px;
transform:rotate(300deg);
-webkit-transform:rotate(300deg);
}
https://codepen.io/YuvarajTana/pen/auiqx
The example is not a repeated background, but with some adjustments maybe it becomes suitable for your need.

Related

GAS PropertiesService to Save and Return Sort Order

QUESTION
How can I use PropertiesService to store an array from index.html, send the array to code.gs, and return the array in index.html?
SPECIFIC CASE
In a Google Web App, I have a group of sortable lists (made using JQuery UI Sortable). I want to save the most recent order/position of each li. I'm attempting to have that order/position "persist" when the page is refreshed or closed.
EXAMPLE
If you see the default Sortable, you could change the order of the items. If you refreshed the page, or closed it and return, the items would be in their original order.
WHERE I'M HAVING TROUBLE
I am able to get the array to show up in the console, but I don't know how to get it back to code.gs. I think I am now, but I'm not sure. Beyond that, I don't know how to "read" that PropertiesService so that the array is returned to index.html. I'm not really sure what I'm doing so if someone could slow walk me it would be appreciated!
ALTERNATIVES
I also looked into writing directly to the spreadsheet where the values originate. I'm not really sure how to do that either. I made some attempts, and was able to get "undefined" as a value in a spreadsheet cell.
FULL CODE (note: the list items are formed using an array, so they will not show up here): https://jsfiddle.net/nateomardavis/Lmcjzho2/1/
PARTIAL CODE
code.gs
function doGet() {
return HtmlService.createHtmlOutputFromFile('index');
}
function webAppTest() {
getTeamArray();
}
function getTeamArray() {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName('TEST');
var range = sheet.getRange(2, 1, 1000, 1);
var values = range.getValues();
var teamsArray = [];
for (var i = 0; i < values.length; ++i) {
teamsArray.push(values[i][0]);
}
var uniqueArray = [];
uniqueArray.push(teamsArray[0]);
for (var i in teamsArray) {
if ((uniqueArray[uniqueArray.length - 1] != teamsArray[i]) && (teamsArray[i] !== "")) {
uniqueArray.push(teamsArray[i]);
}
}
return uniqueArray;
}
function savePositions(myProperty, positions) {
PropertiesService.getScriptProperties().setProperty("myProperty", JSON.stringify(positions));
};
function getPositions() {
var returnedObj = PropertiesService.getScriptProperties()
};
index.html
<body>
<div id="myList" class="connectedSortable">MY LIST</div>
<table id=table1>
<div id="team1">
<p>TEAM 1</p>
<br>
<div id="group" v>SELECTED</div>
<ul id="team1s" name='team1s' class="connectedSortable"></ul>
<div id="group">ALTERNATE</div>
<ul id="team1a" name='team1a' class="connectedSortable"></ul>
</div>
</table>
<table id=table2>
<div id="team2">
<p>TEAM 2</p>
<br>
<div id="group" v>SELECTED</div>
<ul id="team2s" name='team2s' class="connectedSortable"></ul>
<div id="group">ALTERNATE</div>
<ul id="team2a" name='team2a' class="connectedSortable"></ul>
</div>
</table>
<table id=table3>
<div id="team3">
<p>TEAM 3</p>
<br>
<div id="group" v>SELECTED</div>
<ul id="team3s" name='team3s' class="connectedSortable"></ul>
<div id="group">ALTERNATE</div>
<ul id="team3a" name='team3a' class="connectedSortable"></ul>
</div>
</table>
<table id=table4>
<div id="team4">
<p>TEAM 4</p>
<br>
<div id="group" v>SELECTED</div>
<ul id="team4s" name='team4s' class="connectedSortable"></ul>
<div id="group">ALTERNATE</div>
<ul id="team4a" name='team4a' class="connectedSortable"></ul>
</div>
</table>
<script>
$(function() {
google.script.run.withSuccessHandler(buildOptionsList)
.getTeamArray();
});
function buildOptionsList(uniqueArray) {
var div = document.getElementById('myList');
for (var i = 0; i < uniqueArray.length; i++) {
var ul = document.createElement('ul');
var li = document.createElement('li');
var cLass = li.setAttribute('class', 'ui-state-default');
var iD = li.setAttribute('id', uniqueArray[i]);
li.appendChild(document.createTextNode(uniqueArray[i]));
div.appendChild(ul);
div.appendChild(li);
}
}
$(function() {
$("#myList, #team1s, #team1a, #team2s, #team2a, #team2s, #team3s, #team3a, #team4s, #team4a").sortable({
connectWith: ".connectedSortable",
update: function(event, ui) {
var changedList = this.id;
var order = $(this).sortable('toArray');
var positions = order.join(';');
console.log({
id: changedList,
positions: positions
});
//Instead of using JSON to save, can I use the spreadsheet itself to save the positions and then pull it from there as I did with "buildOptionsList" above?
function saveList() {
google.script.run.savePositions("myProperty", JSON.stringify(positions));
JSON.parse("myProperty");
}
}
})
});
$(function getPositions(event, ui) {
var changedList = this.id;
var order = $(this).sortable('toArray');
var positions = order.join(';');
console.log({
id: changedList,
positions: positions
});
});
</script>
</body>
</html>
It's also possible to just use the browser's localStorage client side.
localStorage.setItem('id', positions); //Store positions in users browser
localStorage.getItem('id'); //Retrieve the stored positions later
Notes:
For this to work, the url(document.domain of the iframe="*.googleusercontent.com") from which your script is deployed must remain constant. During my brief testing, it was constant even when changing from /dev to /exec of the parent(script.google.com) and even during version update. But there's no official reference.
This solution is better than properties service, if you have multiple users, as each one will have their own data stored in their own browsers and there are no server calls during each change.
Using google.script.run simple example:
<script>
function sendStringToServer() {
var string=$('#text1').val();
google.script.run
.withSuccessHandler(function(s){
alert(s);
})
.saveString(string);
}
</script>
Google Script:
function myFunction() {
PropertiesService.getScriptProperties().setProperty('MyString', string);
return "String was saved in Service";
}
Client to Server Communication

jquery mobile button refresh and multiple binding

I've a problem with Jquery Mobile. Buttons that I add from JS are not displayed properly, and lacks CSS. On the other hand, hitting a button calls that function, but if another button is clicked, because of on off tap, problem occurs. "addExerciseButton" lacks CSS, and the problem occurs within addExerciseButton
<div data-role="page" id="addprogram">
<div data-role="header" data-position="fixed">
<h1>Add Program</h1>
Back
Save
</div><!-- /header -->
<div data-role="content" class='addprogramcontent'>
<div data-role="fieldcontain" class='addprogramlist'>
</div>
</div>
</div><!-- /page -->
JS:
$(document).off("tap").on('tap', '.addExerciseButton', function(event){
//alert(1);
var container = $(this).attr('id');
alert(container);
});
JS page:
eArray.sort();
var container = $("#addprogram").find(".addprogramlist");
container.empty();
// alert(eArray);
for(var i = 1; i <=7; i++)
{
var day = getDay(i);
container.append("<label for='day-" + i + "' class='select'>" + day + "</label>");
var select = $("<select name='day-" + i + "' id='day-" + i + "'></select>");
for (var j = 0; j < eArray.length; j++)
{
select.append("<option value='" + eArray[j] + "'>" + eArray[j] + "</option>");
}
container.append(select);
var addExerciseButton = "<input type='button' value='Add Exercise' class='addExerciseButton' data-role='button' data-theme='b' id='day-" + i + "'/>"
container.append(addExerciseButton);
}
$("select").selectmenu();
$("#day-1").change(function() {
// alert(value);
$("#day-1 option:selected").each(function () {
// alert(1);
var value = $(this).val();
$(this).parent().selectmenu('disable');
alert(value);
});
});
});
you have to refresh buttons after you append em to the dom:
working example: http://jsfiddle.net/PG2bV/55/
CODE
$(":button").button();
Using
container.trigger('create');
solved my problem with no CSS on buttons.

Jquery Mobile val() returns undefined after changePage

I have 2 pages that I'm working with: first being the page where the values are being fetched from php server and populating the selects/inputs and the second page being a dialog box that fetches the value from the hidden inputs in the first page. The first transition opens the dialog box and fetches the values properly. After which I save the values in php session and reload the first page. After this process when I open the dialog box again the jquery is not able to fetch val() and shows undefined. I'm not sure if this is due to some reloading of the page issue or something else. If I refresh the page then it will work fine again.
<div data-role="page" id="page1">
<div data-theme="a" data-role="header">
.....
<div data-role="navbar" data-iconpos="top">
.....
</div>
<div data-theme="c" id="cashtab" data-role="content">
<div style="display:none" id="proddata" data=""></div>
<div style="display:none" id="prodstock" data=""></div>
<form id="mainsubmit" action="form.php" method="post" data-ajax="false">
<input id="formproduct" type="hidden" name="product" value=""/>
<div id="productsearch" style="width:48%; float:left; margin-right:2%;">
<label for="search">Search Product:</label><br/><br/>
<ul id="productautocomplete" data-role="listview" data-inset="true" data-filter="true" data-filter-placeholder="Select a product... (type at least 3 letters)" data-filter-theme="d"></ul>
</div>
<div id="packingselect" style=" width:23%; float:left; margin-right:2%;">
<label for="packing">Select Packing:</label>
<select name="packing" id="packing" data-iconpos="left">
</select>
</div>
<div id="qtyenter" style=" width:23%; float:left; margin-right:2%;">
<label for="quantity">Select Qty:</label>
<input type="number" data-clear-btn="true" name="quantity" id="qty" value=""/>
</div><br/><br/><br/><br/><br/><br/><br/><br/>
<div style="display:inline-block; width:33%; margin-left:33%; margin-right:33%;">
<a href="#page3" data-rel="dialog" data-role="button" >ADD</a>
</div>
</form>
</div>
</div>
<div data-role="page" id="page3" data-url="dialog.html" data-close-btn="right">
<div data-role="header">
<h1>Batch Selection</h1>
</div>
<div data-role="content">
<div style="overflow:auto;">
<table id="batchsel" style="border:1px;">
<thead>
<tr>
<th></th>
<th>Batch No</th>
<th>Exp Date</th>
<th>Brate</th>
<th>Srate</th>
<th>Packing</th>
<th>Stock</th>
<th>Supplier</th>
<th>ST%</th>
<th>Bill Date</th>
<th>Bill No</th>
<th>btax</th>
</tr>
</thead>
<!--data populated from server once the values from first page is read properly.
<!-- currently not loading the second time as unable to fetch val() -- >
<tbody>
</tbody>
</table>
</div>
<div id="remainingdata">
<p1 id="changeable_requirements"></p1>
<!-- function the send the checked checkboxes relavent info to store in session -->
<button id="saveprod" onclick="addProduct(); return false;">Add Product</button>
</div>
</div>
</div>
<script>
$( document ).on( "pageinit", "#page1", function() {
//for product select autopopulate -- working //
$("#productautocomplete").live( "listviewbeforefilter", function ( e, data ) {
var $ul = $( this ),$input = $( data.input ),value = $input.val(),html = "";
$ul.html( "" );
if ( value && value.length > 2 ) {
$ul.html( "<li><div class='ui-loader'><span class='ui-icon ui-icon-loading'></span></div></li>" );
$ul.listview( "refresh" );
$.getJSON('ajax/getProductList.php', {term:$input.val()}, function(data) {
var items = [];
var str = "";
for (var key in data) {
if (data.hasOwnProperty(key)) {
var value = data[key].value;
var label = data[key].label;
var stock = data[key].stock;
var proddata = data[key].data;
str += '<li code="'+value+'" name="'+label+'" stock="'+stock+'" data="'+proddata+'">';
str += '<a data-ajax="false" rel="external">'+label+' [ '+stock+' ]</a>';
str += '</li>';
}
}
$ul.html( str );
$ul.listview( "refresh" );
$ul.trigger( "updatelayout" );
});
}
});
//end search
//on click set hidden input fields to be used in dialog box. -- working
$('#productautocomplete li').live('click', function(e) {
//--------------------fetch data ------------------------
var id = $(this).attr('code');
var name = $(this).attr('name');
var data = $(this).attr('data');
var stock = $(this).attr('stock');
//add packaging type and unit info to div data
$('#proddata').attr('data',data);
//add currstock info to div
$('#prodstock').attr('data',stock);
//----------------------hide list
$('#productautocomplete li').hide();
//----------------------place name in visible input box
$('#productsearch input').attr('value',name);
//----------------------place id in hidden input box for the actual form.
$('#formproduct').val(id);
//----------------------fill options for package + show select package div
var filteroptions = data.split(",");
$('#packing option').remove();
for (var x=0; x<3 ; x++) {
var eachoption = filteroptions[x].split(":");
//if unit wise option is less than that of stock show as option.
if (eachoption[0]!="0" && eachoption[0] <= stock.valueOf()) {
$('#packing').append($('<option>', {
value: eachoption[0]+':'+eachoption[1],
text : eachoption[1]+' [ '+eachoption[0]+' ] '
}));
}
}
});
});
//this is where the problem lies ..
//have tried with pageinit.. but that only calls it once.
$( document ).on( "pageshow", "#page3", function() {
$('#batchsel tbody').empty();
// !!!!!!!!!!!!!!!!!!!!!!! // !!!!!!!!!!!!!!!!!!!!!!! //
//doesnt fetch any of 4 following values after pageChange back to page1.
//not sure if this is due to how i'm reloading the page1.
//see function addProduct below.
var prodcode = $('#formproduct').val(); //
var prodstock = $('#prodstock').attr('data');
var prodqty = $('#qty').val();
var packing = $('#packing').find(":selected").val();
//returns undefined
alert(prodcode); alert(packing); alert(prodqty);
//always ends here when dialog opens second time.
if (!prodcode || !packing || !prodqty) {
alert("Please give all required information");
//does not close also when opens the second time.
$('#page3').dialog('close');
}
var packinginfo = packing.split(":");
var totalrequired = prodqty * packinginfo[0];
//alert(packinginfo[1]);alert(totalrequired);
if (totalrequired > prodstock ) {
alert("Not enough Stock");
$('#page3').dialog('close');
} else {
//------------------------------ Getting Batch Info ---------------------------------------------------
var rows = '';
$.getJSON('ajax/getBatchDetails.php', {code:prodcode,pack:packinginfo[1],qty:totalrequired}, function(data) {
for (var key in data) {
if (data.hasOwnProperty(key)) {
//alert (data[key].Batch);
rows += '<tr><td><input type="checkbox" class="batchcheckbox" id="batchcheckbox_'+data[key].BatchId+'" value="'+data[key].BatchId+':'+data[key].Stock+'" onchange="resetRemainingQty(this.value);""/></td><td>' + data[key].Batch + '</td><td>' + data[key].ExDt +'</td><td>' + data[key].BRate + '</td><td>' + data[key].SRate + '</td><td>' + data[key].Pack + '</td><td>' + data[key].Stock + '</td><td>' + data[key].Supname + '</td><td>' + data[key].Stax + '</td><td>' + data[key].BillDt + '</td><td>' + data[key].BillNo + '</td><td>' + data[key].btax + '</td><tr>';
}
}
$('#batchsel tbody').append(rows);
//add remaining amount in the data field of p1.
$('#remainingdata p1').attr('data',totalrequired);
$('#remainingdata p2').attr('data',totalrequired);
$('#remainingdata p1').html("<h4>Remaining Amount : "+totalrequired+"</h4>");
});
//---------------------------------------------end batch info display: -----------------------------------
}
});
function addProduct() {
//--------code info---------
var prodcode = $("#formproduct").val(); // to send
//--------packing info---------------
var packing = $('#packing').find(":selected").val();
var packinginfo = packing.split(":");
//-----------qty req ---------------------
var prodqty = $('#qty').val();
var totalrequired = prodqty * packinginfo[0]; // to send
//-------------batch info -----------
var allbatchids = "";
$('.batchcheckbox').each(function() {
if($(this).is(':checked')){
var data = $(this).val();
var datasplit = data.split(":");
var batchid = datasplit[0];
allbatchids += batchid+":";
}
});
allbatchids = allbatchids.substring(0, allbatchids.length - 1); // to send
alert(prodcode+",,"+packinginfo[1]+",,"+totalrequired+",,"+allbatchids);
//-------------- send to server to save to session ---------
$.getJSON('ajax/saveProductSession.php', {code:prodcode,pack:packinginfo[1],qty:totalrequired,batch:allbatchids}, function(data) {
if (data.error == "1") {
alert(data.message);
} else {
/// !!!!!!!! !!!!!!!!!!!!!!! !!!!!!!!!!!!!!!
///
/// the loads the page1. but jquery doesnt take val() after this.
///tried multiple variations of this but to no effect.
///removed all options.. redirect to main.php.. reloadpage:false.. etc.
///Any other way to reload the page so that the dialog once open again can
///get the values from the page1 again.
$.mobile.changePage("#page1", { reloadPage: true , dataUrl : "page1", reverse : true, changeHash: true } );
}
});
//
// $.ajax({
// type: "POST",
// url: "ajax/saveProductSession.php",
// data: { code:prodcode,pack:packinginfo[1],qty:totalrequired,batch:allbatchids }
// }).done(function() {});
}
</script>
Ok ! I got it to work ! thanks anyway #Gajotres. Steps :
1a. Send out the variables from main.php through changePage :
var prodcode = $('#formproduct').val();
var prodstock = $('#prodstock').attr('data');
var prodqty = $('#qty').val();
var packing = $('#packing').find(":selected").val();
$.mobile.changePage('batch.php', {
role: 'dialog',
data: {'prodcode': prodcode,'prodstock': prodstock, 'prodqty' : prodqty , 'packing' : packing},
type: 'get'
});
2a. Moved the entire div id 'page3' to a new php page named 'batch.php' where I get the variables from php and set it to the html divs.
<?php
extract($_GET);
if (!$prodcode && !$prodstock && !$packing && !$prodqty) {
header('Location: '.DEF_SITEURL."main.php");
exit;
}
?>
<div data-role="page" id="batchpage" data-url="batch.php" data-close-btn="right">
<div data-role="header">
<h1>Batch Selection</h1>
</div>
<div data-role="content">
<div style="display:none;" id="batchprodcode" data="<?php echo $prodcode; ?>"></div>
<div style="display:none;" id="batchprodstock" data="<?php echo $prodstock; ?>"></div>
<div style="display:none;" id="batchpacking" data="<?php echo $packing; ?>"></div>
<div style="display:none;" id="batchqty" data="<?php echo $prodqty; ?>"></div>
<div style="overflow:auto;">
<table id="batchsel" style="border:1px;">
<thead>
<tr>
<th></th>
<th>Batch No</th>
<th>Exp Date</th>
<th>Brate</th>
<th>Srate</th>
<th>Packing</th>
<th>Stock</th>
<th>Supplier</th>
<th>ST%</th>
<th>Bill Date</th>
<th>Bill No</th>
<th>btax</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<div id="remainingdata">
<p1 id="changeable_requirements"></p1>
<button id="saveprod" onclick="addProduct(); return false;">Add Product</button>
</div>
</div>
</div>
3a. Then I just change the pageshow that i was using for page3 to the new div that is created on batch.php. The script still runs on main.php.
$( document ).on( "pageshow", "#batchpage", function() {
$('#batchsel tbody').empty();
var prodcode = $('#batchprodcode').attr('data');
var prodstock = $('#batchprodstock').attr('data');
var prodqty = $('#batchqty').attr('data');
var packing = $('#batchpacking').attr('data');
...
});

Show image preview after image upload

My view contains detail of various employees and I have to upload image for each and save at last.I want to see image preview for each image before save but it takes localhost path and do not show image preview.
It's showing error :"NetworkError: 404 Not Found -localhost:3000/rails.png"
In View
<% #person.each do |person| %>
<td><%= person.name %></td>
<td><%= person.date %></td>
<td><input id="<%= person.id %>" type='file' class="imageUploader" multiple="true" ></td>
<td class="image_container"> <img id="image_<%= person.id %>" src="#" alt="Image" width="100" height="100"></td>` here
</tr>
<% end %>
In appliction.js::
$('.imageUploader').change(function() {
var target_image = $(this).val();
$(this).parent('td').parent("tr").children('td.image_container').html("<img src="+target_image+">");
console.log(target_image);
});
Guyz,
Got another one.............`
FILEFIELD = {}
$(document).ready(function() {
$('.files').change(function() {
FILEFIELD = $(this)
var fr = new FileReader;
fr.onload = function() {
var img = new Image;
img.onload = function() {
var c=$(FILEFIELD).parent("td").parent("tr").children("td").children(".images")[0];
var ctx=c.getContext("2d");
ctx.drawImage(img,0,0,50,50);
}
img.src = fr.result;
};
fr.readAsDataURL(this.files[0]);
});
});
And finally working
Well I tried for what you said and got the image preview in my application doing so:
My view:
<% if current_user %>
<p>Welcome <%= current_user.email %></p>
<tr><input type="file" id="files" name="files[]" multiple />
<img id="list" src="#" alt="Image" width="100" height="100"></img></tr>
<% end %>
<style>
.thumb {
height: 75px;
border: 1px solid #000;
margin: 10px 5px 0 0;
}
</style>
<script type="text/javascript">
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="', e.target.result,
'" title="', escape(theFile.name), '"/>'].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
As you see above code is done by me taking into account a single user image preview before upload. But the same you can do for multiple users by changing the query and a little code for multiple users.
Cheers!

How to load a javascript chart on the 2nd, 3rd etc. page in JQuery mobile?

I am quite new to JQuery Mobile and I've been spending days now to figure out an apparently simple question.
Here's my problem:
I am using a charting javascript library from Amcharts. So far, so good...
What I am trying now is just to create a simple page in JQmobile with let's say 2 links to new pages. All I want is when I click the link, the amchart should display in the div with a specific name.
(Amcharts usually displays the chart in a certain div by calling chart.write('nameofthediv');
So I thought with an event handler bound to $('#container').bind('click', function(){...} I should be able just to include the relevant javascript...
Somehow though...it doesn't work.
Here's the link so you can see what I mean:
http://www.noten-werkstatt.de/jqm_amcharts/
And here is the code from the index.html and the relevant custom-scripting.js.
Thank you very much in advance!
Regards,
Lisa
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jQuery Mobile and Amcharts</title>
<link href="amcharts/style.css" rel="stylesheet" type="text/css"> <!-- Amcharts CSS-File local -->
<link href="http://code.jquery.com/mobile/1.0a3/jquery.mobile-1.0a3.min.css" rel="stylesheet" type="text/css"/> <!-- JQ Mobile CSS-File (CDN) -->
<script src="amcharts/amcharts.js" type="text/javascript"></script> <!-- Amcharts JS-File local -->
<script src="http://code.jquery.com/jquery-1.5.min.js" type="text/javascript"></script> <!-- JQ JS-File (CDN) -->
<script src="http://code.jquery.com/mobile/1.0a3/jquery.mobile-1.0a3.min.js" type="text/javascript"></script> <!-- JQ Mobile JS-File (CDN) -->
<script src="custom-scripting.js" type="text/javascript"></script> <!-- Custom Scripting JS-File local -->
</head>
<body>
<!-- ****** START PAGE ************ -->
<div data-role="page" id="page">
<div data-role="header">
<h1>Main Page</h1>
</div>
<div data-role="content">
<ul data-role="listview">
<li>Page two</li>
<li>Page three</li>
</ul>
</div>
<div id="chartserialdiv" style="height:500px !important; border: 1px solid;">It's odd...displaying the chart works here (div containr #chartserialdiv)...(Initialized in the window.onload = function() {})<br>But as I want to attach it to a click handler, please click "page two"...
</div><br>
<div data-role="footer">
<h4>Footer</h4>
</div>
</div>
<!-- ****** 2nd PAGE ************ -->
<div data-role="page" id="page2">
<div data-role="header">
<h1>Page two</h1>
</div>
<div data-role="content" id="test"> <!-- ****** DIV CONTAINER "TEST" ************ -->
If the event handler worked, there must be text after the ":" :<br>
</div>
<div data-role="content" id="chartserialdiv2" style="height:500px !important; border: 1px solid;"> <!-- ****** DIV CONTAINER "CHARTSERIALDIV" ************ -->
The is the div container #chartserialdiv2 - Why is the chart not displaying here???
</div>
<div data-role="footer">
<h4>Footer</h4>
</div>
</div>
<!-- ****** 3rd PAGE ************ -->
<div data-role="page" id="page3">
<div data-role="header">
<h1>Page three</h1>
</div>
<div data-role="content">
As there is no event handler attached to page 3, if you read the text and nothing else happens - that's correct! :-)
</div>
<div data-role="footer">
<h4>Footer</h4>
</div>
</div>
</body>
</html>
custom-scripting.js
window.onload = function() {
//This displays the chart on the start page
var chart;
var dataProvider;
createChart('chartserialdiv');
loadCSV("daten/budget_management_projekt_kum.csv"); //DATENQUELLE
//This is supposed to display the chart on the 2nd page when clicked on the link
$('#page li a.page2').bind('click', function(event){
alert("The link \"Page 2\" was clicked...now we turn to page 2 and try to load the chart...");
$('#test').append("Event Handler-Check: Congratulations, the event handler $(\'#test\').append... worked!!!<br>");
$('#chartserialdiv2').ready(function(){
var chart;
var dataProvider;
createChart('chartserialdiv2');
loadCSV("daten/budget_management_projekt_kum.csv"); //DATENQUELLE
});
//event.preventDefault();
//return false;
});
$(document).delegate('.ui-page', 'pageshow', function () {
alert("worked");
var chart;
var dataProvider;
createChart('chartserialdiv2');
loadCSV("daten/budget_management_projekt_kum.csv"); //DATENQUELLE
});
}
// method which loads external data
function loadCSV(file) {
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
var request = new XMLHttpRequest();
}
else {
// code for IE6, IE5
var request = new ActiveXObject('Microsoft.XMLHTTP');
}
// load
request.open('GET', file, false);
request.send();
parseCSV(request.responseText);
}
// method which parses csv data
function parseCSV(data){
data = data.replace (/,/g,"."); // SUCHE NACH KOMMA UND ERSETZE DURCH PUNKT
var rows = data.split("\r"); // SUCHE NACH ZEILENUMBRUCH UND SPALTE DORT ZEILE AB
dataProvider = [];
for (var i = 1; i < rows.length; i++){ // i=1 WEGEN DER ÜBERSCHRIFTEN
if (rows[i]) {
var column = rows[i].split(";");
var category = column[0];
var value1 = column[1];
var value2 = column[2];
var value3 = column[3];
var dataObject = {category:category, value1:value1, value2:value2, value3:value3};
dataProvider.push(dataObject);
}
}
chart.dataProvider = dataProvider;
chart.validateData();
}
function createChart(container){ // method which creates chart
chart = new AmCharts.AmSerialChart(); // chart variable is declared in the top
chart.addTitle('Chart',12, '#FFFFFF', 1, true);
chart.addLabel(15, 25, 'Mio. €', 'left', 10, '#000000', 0, 1, true);
chart.backgroundAlpha = 1;
chart.backgroundColor = '#FFFFFF';
chart.categoryField = "category"; // here we tell the chart name of category field in our data provider. Wwe called it "date" (look at parseCSV method)
var graph = new AmCharts.AmGraph(); // chart must have at least 1 graph
graph.valueField = "value1"; // graph should know at what field from data provider it should get values.
graph.lineThickness = 3;
graph.lineColor = "#336699";
graph.type = "column";
graph.bulletAlpha = 1;
graph.balloonText = "PLAN kum.:[[value]] Mio. €";
graph.title = "PLAN kum.";
graph.fillAlphas = 1;
chart.addGraph(graph); // add graph to the chart
var graph2 = new AmCharts.AmGraph();
graph2.valueField = "value2"
graph2.lineThickness = 3;
graph2.bullet = "bubble";
graph2.balloonText = "IST kum.:[[value]] Mio. €";
graph2.title = "IST kum.";
graph2.lineColor = "#ff9933";
chart.addGraph(graph2);
var graph3 = new AmCharts.AmGraph();
graph3.valueField = "value3";
graph3.lineThickness = 5;
graph3.bulletAlpha = 1;
graph3.lineColor = "#999999";
graph3.type = "column";
graph3.fillAlphas = 1;
graph3.dashLength = 5;
graph3.balloonText = "Forecast kum.:[[value]] Mio. €";
graph3.title = "Forecast kum.";
chart.addGraph(graph3);
var legend = new AmCharts.AmLegend();
chart.addLegend(legend);
legend.align = "center";
legend.backgroundAlpha = 1;
legend.backgroundColor ="#CCCCCC";
legend.borderAlpha = 1;
legend.borderColor = "#000000";
legend.equalWidths =true;
legend.horizontalGap = 1;
legend.switchType = "v";
legend.markerBorderAlpha = 1;
legend.markerBorderThickness = 1;
legend.markerBorderColor = "#FFFFFF";
legend.markerLabelGap = 5;
legend.position = "bottom";
// 'chartserialdiv' is id of a container where the chart will be
chart.write(container);
}
You need to place your code to generate the chart in the pagshow event, something like
$(document).delegate('#page2', 'pageshow', function( ) {
createChart('chartserialdiv2');
loadCSV("daten/budget_management_projekt_kum.csv");
});

Resources