Adding dynamic alerts (with fixed position) using HTML5/Bootstrap and Javascript? - javascript

I want to add alerts to the top of a web page. The javascript is as follows;
window.onload = function () {
var dps = []; // dataPoints
var chart = new CanvasJS.Chart("chartContainer",{
title :{
text: "Cell 1 Temperature (\xB0C)"
},
axisX: {
title:"Time (seconds)",
},
axisY:{
title: "Temperature (\xB0C)",
},
data: [{
type: "line",
dataPoints: dps
}]
});
var xVal = 0;
var yVal = 100;
var updateInterval = 100;
var dataLength = 5000; // number of dataPoints visible at any point
var updateChart = function (count) {
count = count || 1;
// count is number of times loop runs to generate random dataPoints.
for (var j = 0; j < count; j++) {
yVal = yVal + Math.round(5 + Math.random() *(-5-5));
dps.push({
x: xVal,
y: yVal
});
xVal++;
};
if (dps.length > dataLength)
{
dps.shift();
}
chart.render();
//print stuff
document.getElementById("cell1").innerHTML=yVal + "°C";
};
// generates first set of dataPoints
updateChart(dataLength);
// update chart after specified time.
setInterval(function(){updateChart()}, updateInterval);
}
Essentially when that yVal variable is less than -100 or greater than 100 I want to print an alert dialog to the top of the web page. I want the alert to disappear when the value goes back between -100 and 100. I also want the alert to be fixed to the top of the web page so when it does appear it remains there even if the user scrolls down.
I attempted to add the following code to the javascript:
if (-100>yVal>100) {
document.getElementById("alert1").innerHTML="DANGA'";
} else {
document.getElementById("alert2").innerHTML="S'All GOOOD";
}
and have the following alerts in the HTML:
<div class="alert alert-danger" style="position: fixed" id="alert1"></div>
<div class="alert alert-success" style="position: fixed" id="alert2"></div>
But there are several problems. First, once triggered these alerts never change. And to begin with these alerts are always present, there just isn't any text in them until triggered.
If someone knew a way to have these alerts appear and disappear only when desired, and when present to remain in a fixed position, that would be appreciated.
Thanks

Related

Showing Progress while Child row loads

Coming again with another question :)
This time I had a requirement to show some progress while Child rows are being loaded. Since there is an Api call which relatively takes little time to return data, I do want to show the some progress unless the user who clicks the parent row is totally unaware whether there is a call done to see its child rows.
What I have done:
I wrote a style sheet class which has a
loader-small.gif
image as this:
tr.loading td.details-control {
background: url('/Images/loader-small.gif') no-repeat center center;
}
and applied like this:
$('#accountManagerEarningsDataTable tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = table.row(tr);
try {
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
//Calling the loading Class ------>
tr.addClass('loading');
// Open this row
var arrForTable1 = [];
var arrForTable2 = [];
totalBrokerage = 0;
totalRetailBrokerage = 0;
totalSelfServiceBrokerage = 0;
console.log('You selected: ' + row.data().AccountManagerID);
var settings = {
"columnDefs": [
{ targets: 1, align: "right", decimals: 0 },
{ targets: 2, align: "right", decimals: 0 },
{ targets: 3, align: "right", decimals: 0 },
{ targets: 4, align: "right", decimals: 2 },
{ targets: 5, align: "right", decimals: 2 }
]
};
//problems with asynchoronus call back
var response = organization_GetAccountManagerDetailEarningsAccountData(row.data(), purl2, pcontext);
if (response.success === "true") {
for (var i = 0; i < response.value.length; i++) {
for (var j = 0; j < response.value[i].Securities.length; j++) {
var itemRow2 = {};
itemRow2["Security ID"] = response.value[i].Securities[j].SecurityId;
itemRow2["Trades"] = response.value[i].Securities[j].Trades;
itemRow2["Buy Qty"] = response.value[i].Securities[j].BuyQuantity;
itemRow2["Sell Qty"] = response.value[i].Securities[j].SellQuantity;
itemRow2["Total Brkg"] = response.value[i].Securities[j].Effective_Brokerage;
itemRow2["Online Brkg"] = response.value[i].Securities[j].Online_Brokerage;
arrForTable2.push(itemRow2);
totalBrokerage = totalBrokerage + parseFloat(response.value[i].Securities[j].Effective_Brokerage);
totalSelfServiceBrokerage = totalSelfServiceBrokerage + parseFloat(response.value[i].Securities[j].Online_Brokerage);
}
totalBrokerage = Math.round(totalBrokerage * 100) / 100;
totalSelfServiceBrokerage = Math.round(totalSelfServiceBrokerage * 100) / 100;
totalRetailBrokerage = Math.round(totalRetailBrokerage * 100) / 100;
var itemRow1 = {};
itemRow1["Account ID"] = response.value[i].AccountId;
itemRow1["Account Name"] = response.value[i].AccountName;
itemRow1["..."] = '<div class="alert alert-info" role="alert">' + buildHtmlTable(arrForTable2, 'table2x' + j, settings) + '<p>Total Brokerage ' + numberWithCommas(totalBrokerage) + '</p></div>';
arrForTable1.push(itemRow1);
arrForTable2 = [];
totalBrokerage = 0;
totalRetailBrokerage = 0;
totalSelfServiceBrokerage = 0;
}
tr.removeClass('loading');
htmlTable1 = buildHtmlTable(arrForTable1, 'table1x' + i);
row.child(htmlTable1).show();
tr.addClass('shown');
}
else {
row.child('<table><tr><td>' + response.value[0].AccountId + '</td></tr></table>').show();
tr.addClass('shown');
};
}
} catch (e) {
console.log(e.message);
}
});
The Problem:
Firefox nicely shows the Progress image after the user clicks it, but Edge and Chrome does not show. Both browsers crossed this piece of code when I was debugging from developer tools of the respective browser.
Its browser compatible problem? Is there a solution for it? Help me please.
In case of chrome there is such an issue while showing the loading bar while making a server call. Please make the following changes where you are making the service call. First add the class loading to the table
tr.addClass('loading');
After that make the service call by giving a timeout function
setTimeout(function(){
var response = organization_GetAccountManagerDetailEarningsAccountData(row.data(), purl2, pcontext);
......
//Your service calls and response call backs
},1);
On providing a timeout (say 1ms), Chrome will get the time to bind the loading bar to DOM, In other case the DOM Object is not available to show the spinner.

Getting a canvasjs graph to fit in a collapsed table row in Bootstrap?

I have created a canvasjs graph and want it to fit in a responsive table in Bootstrap.
I have created a large table in Bootstrap/HTML5 with one row defined as follows:
<tr>
<td colspan="100%" class="hiddenRow">
<div class="collapse" id="cellOneExp">
<div id="chartContainer1"></div>
</div>
</td>
</tr>
chartContainer1 refers to a dynamic graph created using canvasjs and has the following code:
window.onload = function () {
var dps = []; // dataPoints
var chart = new CanvasJS.Chart("chartContainer1",{
zoomEnabled: true,
title :{
text: "Cell 1 Temperature (\xB0C)"
},
axisX: {
title:"Time (seconds)",
},
axisY:{
title: "Temperature (\xB0C)",
},
data: [{
type: "line",
dataPoints: dps
}]
});
var xVal = 0;
var yVal = 100;
var updateInterval = 100;
var dataLength = 5000; // number of dataPoints visible at any point
var updateChart = function (count) {
count = count || 1;
// count is number of times loop runs to generate random dataPoints.
for (var j = 0; j < count; j++) {
yVal = yVal + Math.round(5 + Math.random() *(-5-5));
dps.push({
x: xVal,
y: yVal
});
xVal++;
};
if (dps.length > dataLength)
{
dps.shift();
}
chart.render();
if (yVal>"100") {
$('#alertHigh').slideDown(); //callback function will go in the brackets to slide the alert back up
$('#alertLow').slideUp();
} else if (yVal<"-100") {
$('#alertLow').slideDown();
$('#alertHigh').slideUp();
} else {
$('#alertLow').slideUp();
$('#alertHigh').slideUp();
};
//print stuff
document.getElementById("cell1").innerHTML=yVal + "°C";
};
// generates first set of dataPoints
updateChart(dataLength);
// update chart after specified time.
setInterval(function(){updateChart()}, updateInterval); }
The table has a button in it which has the id cellOneExp, so when that button is pressed the table should expand to show the graph.
If is replaced with anything else (for example a p tag) the table expands appropriately. However with the graph present the table does not expand correctly. Instead the graph overlays the rest of the table elements and I cannot figure out how to solve this. Thanks!

Canvas.js slows down

The problem:
The problem I am encountering is that for each "JQuery event" click, the canvas.js diagram slows down proporsjonal to the click? I believe $(document).ready(function(){ is responsible.
That is to say 10 clicks slows down the applciation 10 times. Keep in mind that I have five canvas.js diagrams (tables). Canvas.js
Table1.js (The same code structure goes for the other diagrams, table2,table3 etc).
(function table1(){
$(document).ready(function(){
var dps = []; // data
var chart = new CanvasJS.Chart("table1",
{
title:{
text: "Exhaust Temperature"
data: [
{
type: "spline",
name: "Temp Cylinder 1",
showInLegend: "true",
legendText: "Temp Cylinder 1",
dataPoints: dps1
}
});
var xVal = 0;
var updateInterval = 50;
var dataLength = 50;
var updateChart = function (count) {
count = count || 1;
// count is number of times loop runs to generate random dataPoints.
for (var j = 0; j < count; j++) {
dps.push({
x: xVal,
y: EXTS[1]
});
xVal++;
};
if (dps.length > dataLength )
{
dps.shift();
}
chart.render();
};
// generates first set of dataPoints
updateChart(dataLength);
// update chart after specified time.
setInterval(function(){updateChart()}, updateInterval);
});
}());
This is JQuery event that is responsible for showing and hiding the diagrams, keep in mind that the user can only view one diagram at time.
$('[data-row]').on('click', function() {
var row = $(this).attr('data-row');
$('.active').removeClass('active');
$('#table' + row).addClass('active');
if (row == 1){
$.getScript("table1.js", function(){});
table1();
} else if (row == 2) {
$.getScript("table2.js", function(){});
table2();
} else if (row == 3) {
$.getScript("table3.js", function(){});
table3();
}
});

Insert realtime data in Canvas js

I have been working some days with Canvas JS and made some amazing realtime diagrams, but the problem is; data is only random generated. I have managed to get some data from an sensor, and I wish to insert this data into Canvas JS, and remove random generated data, but I can not figure out how to replace the real data with random generated data?
Just to repeat my question, what modifications do I need to do in order to insert realtime data instead of random generated data?
Here is the code I got from Canvas JS (Code Example from canvasjs).
<script type="text/javascript">
window.onload = function () {
var dps = []; // dataPoints
var chart = new CanvasJS.Chart("chartContainer",{
title :{
text: "Live Random Data"
},
data: [{
type: "line",
dataPoints: dps
}]
});
var xVal = 0;
var yVal = 100;
var updateInterval = 20;
var dataLength = 500; // number of dataPoints visible at any point
var updateChart = function (count) {
count = count || 1;
// count is number of times loop runs to generate random dataPoints.
for (var j = 0; j < count; j++) {
yVal = yVal + Math.round(5 + Math.random() *(-5-5));
dps.push({
x: xVal,
y: yVal
});
xVal++;
};
if (dps.length > dataLength)
{
dps.shift();
}
chart.render();
};
// generates first set of dataPoints
updateChart(dataLength);
// update chart after specified time.
setInterval(function(){updateChart()}, updateInterval);
}
</script>
This should do the job
<script type="text/javascript">
window.onload = function () {
var dps = []; // dataPoints
var ws = new WebSocket("ws://IP(hidden):8081/osc");
var chart = new CanvasJS.Chart("chartContainer",{
title :{
text: "Live Random Data"
},
data: [{
type: "line",
dataPoints: dps
}]
});
var xVal = 0;
var yVal = 100;
var updateInterval = 20;
var dataLength = 500; // number of dataPoints visible at any point
ws.onmessage = function(evt) {
var point = evt.data.split(",");
// To ensure we have recieved both x and y values
if ( point.length === 2 ){
dps.push({
x: parseInt( point[0] ),
y: parseInt( point[1] )
});
}
if (dps.length > dataLength){
dps.shift();
}
chart.render();
}
}
</script>
Thanks for helping me Mr. Lakha Singh Namdhari! The diagram is now receiving data, the only thing I had to do was to remove the if statement around the code. Because this if statement gave me only 0s for dps.length.. The problem was that dps.length was equal to 0 (constant). So when I removed the if statement, the dps.length started to increment correctly.
I have some things left such as design and time delay etc, but I will start a new thread because this questions is solved.
I changed this:
if ( point.length === 2 ){
dps.push({
x: parseInt( point[0] ),
y: parseInt( point[1] )
});
}
To this:
dps.push({
x: parseInt( point[0] ),
y: parseInt( point[1] )
});
I have basically created a diagram where it stores temperature values. Everything works great, the only problem is that the x-axis does not go out from the frame. I want the x-axis to move with the data. Like the link below.
Here is the example!
This is the code, I have hidden the IP for security reasons. What shall I implement in order to make the x-axis move with the data?
<script type="text/javascript">
window.onload = function () {
var dps = []; // dataPoints
// Connect to the server.
var server_url = "ws://";
var ip = 'xxx.xxx.x.xx';
server_url = server_url.concat(ip,":8081/osc")
ws = new WebSocket(server_url);
var chart = new CanvasJS.Chart("chartContainer",{
title :{
text: "Temp Bank Sensor 1 - (TBS1)"
},
data: [{
type: "splineArea",
color: "rgba(255, 0, 29, 0.79)",
dataPoints: dps
}]
});
var xVal = 0;
var yVal = 100;
var updateInterval = 20;
var dataLength = 500; // number of dataPoints visible at any point
ws.onmessage = function(evt) {
var point = evt.data.split(",");
dps.push({
x: xVal,
y: parseInt( point[1] )
});
xVal++;
if (dps.length > dataLength){
dps.shift();
}
chart.render();
} // end method ws.onmessage
// generates first set of dataPoints
updateChart(dataLength);
// update chart after specified time.
setInterval(function(){updateChart()}, updateInterval);
}; // end method window.onload
</script>

How should multiple progress bars be handled in javascript

I have a number of progress bars each tied to a div which are updated using 'setTimeouts'.
An example of how it runs is like this :
myDiv._timer = setTimeout(function () {
func_name(data)
}, 1);
Edit: As requested a working example of my one progress bar: http://jsfiddle.net/H4SCr/
The question however is, I have multiple div's with progression bars with their own data to use to calculate progression. Which means with say 5 on the go i have 5 different timeouts running.
I'm no expert in javascript, but surely theres a way to structure this to tie to just one time out for all progress bars, or is my current approach the best method ?
Note: i don't use jQuery. I prefer to go with just vanilla javascript to learn!
Check this out:
http://jsfiddle.net/MZc8X/11/
I created an array of objects which contains the container id and its increment value.
// array to maintain progress bars
var pbArr = [{
pid: 'bar1', // parent container id
incr: 1 // increment value
}, {
pid: 'bar2',
incr: 2
}, {
pid: 'bar3',
incr: 3
}, {
pid: 'bar4',
incr: 4
}, {
pid: 'bar5',
incr: 5
}];
And, then call a function to create a progress bar...
var loopCnt = 1; // loop count to maintain width
var pb_timeout; // progress bar timeout function
// create progress bar function
var createPB = function () {
var is_all_pb_complete = true; // flag to check whether all progress bar are completed executed
for (var i = 0; i < pbArr.length; i++) {
var childDiv = document.querySelector('#' + pbArr[i].pid + ' div'); // child div
var newWidth = loopCnt * pbArr[i].incr; // new width
if (newWidth <= 100) {
is_all_pb_complete = false;
childDiv.style.width = newWidth + '%';
} else {
childDiv.style.width = '100%';
}
}
if (is_all_pb_complete) { // if true, then clear timeout
clearTimeout(pb_timeout);
return;
}
loopCnt++; // increment loop count
// recall function
pb_timeout = setTimeout(function () {
createPB();
}, 1000);
}
// call function to initiate progress bars
createPB();
Hope, it works for you.

Categories

Resources