Scroll to bottom when new content is added to div - javascript

How can I get the chat to scroll to bottom when new content is sent into the chat? I'm trying to add something like this:
$('#what do I have to put here?').animate({scrollTop: $('#and here?').prop("scrollHeight")}, 200);
but I can't make it work (I have no idea where in the code to place it).
Thanks!
This is an important part of the code... Maybe I have to add it here (but I don't know how or where):
<script type="text/javascript">
var _answerBot = new answerBot();
function keypressInput(sender, event) {
if (event.which == 13) {
document.getElementById('subcontent').innerHTML += _answerBot.processInput(sender.value);
sender.value = '';
}
}
</script>
This is a separate scripts.js file:
var answerBot = function () {
var _this = this;
_this.processInput = function (text) {
updateUrl(text);
var _result = "<p class='answerbot-input'>" + text + "</p>";
text = text.replace(new RegExp("[ ]{2,}", "g"), " ");
var _words = text.toLowerCase().split(" ");
var _answers = [];
var _title = "";
if (_words.length === 0 || _words.toString() === '') { //if the input is empty
_answers = _this.specialContext.emptyInput;
_title = _this.specialContext.emptyInput;
} else {
var _possibleAnswers = findMatches(_words);
if (_possibleAnswers.length === 0) { //if no answer found
_answers = _this.specialContext.wrongInput;
_title = _this.specialContext.wrongInput;
}
if (_possibleAnswers.length == 1) { //context recognized
_answers = _this.answers[_possibleAnswers[0]].values;
_title = _this.answers[_possibleAnswers[0]].description;
}
if (_possibleAnswers.length > 1) {
_result += formatText(_this.specialContext.rephrase, _this.specialContext.rephrase);
for (var i = 0; i < _possibleAnswers.length; i++) {
_result += formatText(_this.answers[_possibleAnswers[i]].description, _this.answers[_possibleAnswers[i]].description);
}
}
}
if (_answers.length > 0) {
var _rand = Math.floor((Math.random() - 0.001) * _answers.length);
_result += formatText(_answers[_rand], _title);
}
return _result;
};
function formatText(text, title) {
return "<p class=\'answerbot-ai\' title=\'" + title + "\'>" + text + "</p>";
}
function findMatches(words) {
var foundKeywords = [];
var _possibleAnswers = [];
for (var i = 0; i < _this.keywords.length; i++) {
foundKeywords[i] = 0;
for (var j = 0; j < words.length; j++) {
if (_this.keywords[i].keys.indexOf(words[j]) >= 0) {
foundKeywords[i]++;
if (foundKeywords[i] == _this.keywords[i].keys.length) {
return [_this.keywords[i].value];
}
}
}
if (foundKeywords[i] * 2 > _this.keywords[i].keys.length) {
_possibleAnswers.push(_this.keywords[i].value);
}
}
return _possibleAnswers.filter(function (elem, pos) {
return _possibleAnswers.indexOf(elem) == pos;
});
}
function updateUrl(text){
history.pushState(null, null, "#question=" + encodeURIComponent(text));
if(typeof ga === "function")//google analytics
ga('send', 'event', 'question', text);
}
};

function AddMessage() {
var $message = $("<p>").text("message");
var $messages = $("#messages");
$messages.append($message);
$messages.animate({
scrollTop: $messages.prop("scrollHeight")
});
}
#messages {
border: 1px solid #000;
height: 100px;
overflow: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="chat">
<div id="messages"></div>
<button onClick="AddMessage()">Add Message</button>
</div>

Related

Execute function on each element (with the same id)

I have this HTML code:
<div id="dadosalvaje" class="draconistone"><dl class="codebox"><dd><strong>Número aleatorio (1,10) : </strong>1</dd></dl></div>
<div id="dadosalvaje" class="draconistone"><dl class="codebox"><dd><strong>Número aleatorio (1,10) : </strong>3</dd></dl></div>
And i want to execute this JavaScript code on each one:
$(document).ready(function() {
//Arreglos
var zonas = ['draconistone','cessabit', 'valoran'];
var draconistone = ['bulbasaur', 'pikachu', 'squirtle'];
//Variables
var contenedor = $('#dadosalvaje');
var texto = contenedor.text().split(' ');
var resultado = texto.pop();
var zonaID = $('#dadosalvaje').attr('class');
for (var i = 0; i < zonas.length; i++) {
if (zonaID == zonas[i]) {
if (zonaID == 'draconistone') {
var pokemonSprite = draconistone[resultado - 1];
}
}
}
for (var i = 0; i < zonas.length; i++) {
if (zonas[i] == zonaID) {
contenedor.append('<img src="https://www.pkparaiso.com/imagenes/xy/sprites/animados/' + pokemonSprite + '.gif"><div class="salvajeNombre">' + pokemonSprite + '</div>');
contenedor.attr('id', 'salvajelisto');
}
}
});
It just affects the first element and I can't find the way to modify both of them.
Is there any way to modify every single element with the same ID ?
First you need to make unique id
You do not need the "draconistone" class
Inside the $(document).ready(function() { and }); tags make the code a function with an id parameter like this:
function name(id) {
//Arreglos
var zonas = ['draconistone','cessabit', 'valoran'];
var draconistone = ['bulbasaur', 'pikachu', 'squirtle'];
//Variables
var contenedor = $('#' + id);
var texto = contenedor.text().split(' ');
var resultado = texto.pop();
var zonaID = $('#' + id).attr('class');
for (var i = 0; i < zonas.length; i++) {
if (zonaID == zonas[i]) {
if (zonaID == 'draconistone') {
var pokemonSprite = draconistone[resultado - 1];
}
}
}
for (var i = 0; i < zonas.length; i++) {
if (zonas[i] == zonaID) {
contenedor.append('<img src="https://www.pkparaiso.com/imagenes/xy/sprites/animados/' + pokemonSprite + '.gif"><div class="salvajeNombre">' + pokemonSprite + '</div>');
contenedor.attr('id', 'salvajelisto');
}
}
}
Then execute the functions with the two different ids as parameters.
Maybe you can use $.each()
Like this
$('.draconistone').each(function() {
var zonaID = $(this).attr('class');
..
});
There is one for the same class
$( document).ready(function() {
$( ".draconistone" ).each(function( i ) {
var zonas = ['draconistone','cessabit', 'valoran'];
var draconistone = ['bulbasaur', 'pikachu', 'squirtle'];
//Variables
var texto = this.innerText.split(' ');
var resultado = texto.pop();
var zonaID = this.className;
for (var i = 0; i < zonas.length; i++) {
if (zonaID == zonas[i]) {
if (zonaID == 'draconistone') {
var pokemonSprite = draconistone[resultado - 1];
}
}
}
for (var i = 0; i < zonas.length; i++) {
if (zonas[i] == zonaID) {
this.innerHTML += '<img src="https://www.pkparaiso.com/imagenes/xy/sprites/animados/' + pokemonSprite + '.gif"><div class="salvajeNombre">' + pokemonSprite + '</div>';
this.id = 'salvajelisto';
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dadosalvaje1" class="draconistone"><dl class="codebox"><dd><strong>Número aleatorio (1,10) : </strong>1</dd></dl></div>
<div id="dadosalvaje2" class="draconistone"><dl class="codebox"><dd><strong>Número aleatorio (1,10) : </strong>3</dd></dl></div>

How to change this code to list post titles of all the post on Blogger in format YYYY.MM.DD <title> and chronological order?

I like to show my titles of posts on a specific page. It is more effective to get know what author have written than scroll all pages or navigate using archive widget.
I found code (code is below) for generate list that sort post titles alphabetically but I like to show titles in chronological order. There is lot of code example about this but they are outdated. They doesn’t work anymore after some changes in blogger platform.
How to change code to get post titles in chronological order and in format YYYY.MM.DD ?
<div>
<ul id="postList12"></ul>
</div>
<script type="text/javascript">
var startIndex = 1;
var maxResults = 150;
var allResults = [];
function sendQuery12() {
var scpt = document.createElement("script");
scpt.src = "/feeds/posts/summary?alt=json&callback=processPostList12&start-index=" + startIndex + "&max-results=" + maxResults;
document.body.appendChild(scpt);
}
function printArrayResults(root) {
//Sort Alphebetically
allResults.sort(function(a, b)
{
var a_string = a.children[0].textContent ;
var b_string = b.children[0].textContent ;
if(a_string < b_string) return -1;
if(a_string > b_string) return 1;
return 0;
})
var elmt = document.getElementById("postList12");
for (index = 0; index < allResults.length; index++) {
elmt.appendChild(allResults[index]);
}
}
function processPostList12(root) {
var elmt = document.getElementById("postList12");
if (!elmt)
return;
var feed = root.feed;
if (feed.entry.length > 0) {
for (var i = 0; i < feed.entry.length; i++) {
var entry = feed.entry[i];
var title = entry.title.$t;
var date = entry.published.$t
for (var j = 0; j < entry.link.length; j++) {
if (entry.link[j].rel == "alternate") {
var url = entry.link[j].href;
if (url && url.length > 0 && title && title.length > 0) {
var liE = document.createElement("li");
var a1E = document.createElement("a");
a1E.href = url;
a1E.textContent = title + " (" + date.substr(0,10) + ")";
liE.appendChild(a1E);
//elmt.appendChild(liE);
allResults.push(liE);
}
break;
}
}
}
if (feed.entry.length >= maxResults) {
startIndex += maxResults;
sendQuery12();
} else {
printArrayResults();
}
}
}
sendQuery12();
</script>
Code is copied from here: https://dansator.blogspot.fi/2015/10/general-alphabetical-list-of-posts.html
Remove sort method from the code. remove the following :
//Sort Alphebetically
allResults.sort(function(a, b){
var a_string = a.children[0].textContent ;
var b_string = b.children[0].textContent ;
if(a_string < b_string) return -1;
if(a_string > b_string) return 1;
return 0;
})
Your code should be
<div>
<ul id="postList12"></ul>
</div>
<script type="text/javascript">
var startIndex = 1;
var maxResults = 150;
var allResults = [];
function sendQuery12()
{
var scpt = document.createElement("script");
scpt.src = "/feeds/posts/summary?alt=json&callback=processPostList12&start-index=" + startIndex + "&max-results=" + maxResults;
document.body.appendChild(scpt);
}
function printArrayResults(root)
{
var elmt = document.getElementById("postList12");
for (index = 0; index < allResults.length; index++) {
elmt.appendChild(allResults[index]);
}
}
function processPostList12(root)
{
var elmt = document.getElementById("postList12");
if (!elmt)
return;
var feed = root.feed;
if (feed.entry.length > 0)
{
for (var i = 0; i < feed.entry.length; i++)
{
var entry = feed.entry[i];
var title = entry.title.$t;
var date = entry.published.$t
for (var j = 0; j < entry.link.length; j++)
{
if (entry.link[j].rel == "alternate")
{
var url = entry.link[j].href;
if (url && url.length > 0 && title && title.length > 0)
{
var liE = document.createElement("li");
var a1E = document.createElement("a");
a1E.href = url;
a1E.textContent = title + " (" + date.substr(0,10) + ")";
liE.appendChild(a1E);
//elmt.appendChild(liE);
allResults.push(liE);
}
break;
}
}
}
if (feed.entry.length >= maxResults)
{
startIndex += maxResults;
sendQuery12();
} else {
printArrayResults();
}
}
}
sendQuery12();
</script>

Missing value from list pulled from array

When I hit my calculate button, the new lists with values pulled from the arrays are visible, but the second array is missing a value.The missing value is not always the same value. For example if I put in 1,2,3,4,5,6, it's not always the same number missing, it's probably the last value in the array, but I can't figure out where I went wrong. Here's the code:
$(document).ready(function() {
function copyarray(arraytocopy) {
var theCopy = []; // An new empty array
for (var i = 0, len = arraytocopy.length; i < len; i++) {
theCopy[i] = arraytocopy[i];
}
return theCopy;
}
function sortarray(arraytosort) {
arraytosort.sort(
function(a, b) {
return Math.round(Math.random());
}
);
return arraytosort;
}
function checkarrays(newarray, oldarray) {
var swappositions = [];
for (var i = 0; i < newarray.length; i++) {
if (newarray[i] == oldarray[i]) {
//alert(oldarray[i] + ' is the SAME!');
swappositions.push(newarray[i]);
}
}
var countsame = 0;
swappositions.reverse();
for (var i = 0; i < newarray.length; i++) {
if (newarray[i] == oldarray[i]) {
///alert(oldarray[i] + ' is the SAME!');
newarray[i] = swappositions[countsame];
countsame = countsame + 1;
}
}
for (var i = 0; i < newarray.length; i++) {
if (newarray[i] == oldarray[i]) {
//alert(oldarray[i] + ' is the SAME!');
//swappositions.push(newarray[i]);
var elementbefore = newarray[i - 1];
newarray[i - 1] = newarray[i];
newarray[i] = elementbefore;
}
}
///alert('test');
///alert('new array: ' + newarray);
///alert('old array: ' + oldarray);
//alert(swappositions.toString());
//alert($.inArray( swappositions[0], newarray ));
return true;
}
Array.prototype.randomize2 = function() {
var oldarray = copyarray(this);
sortarray(this);
var notthesame = checkarrays(this, oldarray);
if (notthesame = false) {
//alert('sort again');
sortarray(this);
notthesame = checkarrays(this, oldarray);
}
//alert('new: '+this);
//alert('old: '+oldarray);
//alert('not the same!');
return this;
};
function makelist(myarray) {
var list = '<ol>';
var listitem = '';
for (var i = 0; i < myarray.length; i++) {
if (/\S/.test(myarray[i])) {
listitem = '<li>' + $.trim(myarray[i]) + '</li>';
list += listitem;
}
}
list += '</ol>';
//alert(list.toString());
return list.toString();
}
function combinelists(ordered, random) {
var list = '<ol>';
var listitem = '';
for (var i = 0; i < ordered.length; i++) {
if (/\S/.test(ordered[i])) {
if ($.trim(random[i]) == $.trim(ordered[i])) {
listitem = '<li class="same"><span class="yourname">' + $.trim(ordered[i]) + '</span> is matched with<span class="peersname">' + $.trim(random[i]) + '</span></li>';
list += listitem;
} else {
listitem = '<li><span class="yourname">' + $.trim(ordered[i]) + '</span> is matched with <span class="peersname">' + $.trim(random[i]) + '</span></li>';
list += listitem;
}
}
}
list += '</ol>';
//alert(list.toString());
return list.toString();
}
$('#ranGen').click(function() {
//function randomize(){
var lines = $('#names').val().split(/\n/);
var texts = [];
for (var i = 0; i < lines.length; i++) {
// only push this line if it contains a non whitespace character.
if (/\S/.test(lines[i])) {
texts.push($.trim(lines[i]));
}
}
var orderedlist = makelist(lines);
//$( "#list" ).html(orderedlist);
var linescopy = $.extend(true, [], lines);
var randomarray = linescopy.randomize2();
//alert(randomarray);
var randomlist = makelist(randomarray);
//$( "#randomlist" ).html(randomlist);
var combinedlists = combinelists(lines, randomarray);
$("#combined").html(combinedlists);
});
});
textarea {
height: 100px;
width: 400px;
}
input {
display: block;
}
.list {
display: inline-block;
}
.same {
color: orange;
}
.yourname {
color: blue;
}
.peersname {
color: brown;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h1>Get a random match </h1>
<p>Insert all your names into the textarea below. Each name should be on a new line. Hit the button to generate your matches.</p>
<form>
<textarea id="names" placeholder="Enter list of names here. Each name should be on a new line."></textarea>
<input type="button" id="ranGen" value="Go" onClick="JavaScript:randomize()" />
</form>
<div id="list" class="list"></div>
<div id="randomlist" class="list"></div>
<div id="combined" class="list"></div>
Filtering out "empty" lines should fix the issue
var lines = $('#names').val().split(/\n/).filter(function (val) {
return val.trim() != '';
});

Blogger related post gadget image Resize s72-c [ Need Expert Help ]

I run a Blogger blog and I use follow code JavaScript code (requires no jQuery) to show the related post with labels/categories of the post.
<script type='text/javascript'>
var defaultnoimage="http://1.bp.blogspot.com/-M72rpgunTq0/VUOKijudN_I/AAAAAAAABoI/LQ18scEunSg/w72/favicon-TIK.png";
var maxresults=16;
var splittercolor="#d4eaf2";
var relatedpoststitle="Related Posts";
</script>
<script type='text/javascript'>//<![CDATA[
var relatedTitles = new Array();
var relatedTitlesNum = 0;
var relatedUrls = new Array();
var thumburl = new Array();
function related_results_labels_thumbs(json) {
for (var i = 0; i < json.feed.entry.length; i++) {
var entry = json.feed.entry[i];
relatedTitles[relatedTitlesNum] = entry.title.$t;
try {
thumburl[relatedTitlesNum] = entry.media$thumbnail.url
} catch (error) {
s = entry.content.$t;
a = s.indexOf("<img");
b = s.indexOf("src=\"", a);
c = s.indexOf("\"", b + 5);
d = s.substr(b + 5, c - b - 5);
if ((a != -1) && (b != -1) && (c != -1) && (d != "")) {
thumburl[relatedTitlesNum] = d
} else {
if (typeof(defaultnoimage) !== 'undefined') {
thumburl[relatedTitlesNum] = defaultnoimage
} else {
thumburl[relatedTitlesNum] = "http://1.bp.blogspot.com/_u4gySN2ZgqE/SosvnavWq0I/AAAAAAAAArk/yL95WlyTqr0/s400/noimage.png"
}
}
}
if (relatedTitles[relatedTitlesNum].length > 80) {
relatedTitles[relatedTitlesNum] = relatedTitles[relatedTitlesNum].substring(0, 80) + "..."
}
for (var k = 0; k < entry.link.length; k++) {
if (entry.link[k].rel == 'alternate') {
relatedUrls[relatedTitlesNum] = entry.link[k].href;
relatedTitlesNum++
}
}
}
}
function removeRelatedDuplicates_thumbs() {
var tmp = new Array(0);
var tmp2 = new Array(0);
var tmp3 = new Array(0);
for (var i = 0; i < relatedUrls.length; i++) {
if (!contains_thumbs(tmp, relatedUrls[i])) {
tmp.length += 1;
tmp[tmp.length - 1] = relatedUrls[i];
tmp2.length += 1;
tmp3.length += 1;
tmp2[tmp2.length - 1] = relatedTitles[i];
tmp3[tmp3.length - 1] = thumburl[i]
}
}
relatedTitles = tmp2;
relatedUrls = tmp;
thumburl = tmp3
}
function contains_thumbs(a, e) {
for (var j = 0; j < a.length; j++) {
if (a[j] == e) {
return true
}
}
return false
}
function printRelatedLabels_thumbs(current) {
var splitbarcolor;
if (typeof(splittercolor) !== 'undefined') {
splitbarcolor = splittercolor
} else {
splitbarcolor = "#d4eaf2"
}
for (var i = 0; i < relatedUrls.length; i++) {
if ((relatedUrls[i] == current) || (!relatedTitles[i])) {
relatedUrls.splice(i, 1);
relatedTitles.splice(i, 1);
thumburl.splice(i, 1);
i--
}
}
var r = Math.floor((relatedTitles.length - 1) * Math.random());
var i = 0;
if (relatedTitles.length > 0) {
document.write('<div class="title">' + relatedpoststitle + '</div>')
}
document.write('<div style="clear: both;"/>');
while (i < relatedTitles.length && i < 20 && i < maxresults) {
document.write(' <img src="' + thumburl[r] + '"/><br/><div class="relatedpostitle" >' + relatedTitles[r] + '</div>');
i++;
if (r < relatedTitles.length - 1) {
r++
} else {
r = 0
}
}
document.write('</div>');
relatedUrls.splice(0, relatedUrls.length);
thumburl.splice(0, thumburl.length);
relatedTitles.splice(0, relatedTitles.length)
}
//]]></script>
<div id='related-posts'>
<b:loop values='data:post.labels' var='label'>
<b:if cond='data:label.isLast != "true"'/>
<script expr:src='"/feeds/posts/summary/-/" + data:label.name + "?alt=json-in-script&callback=related_results_labels_thumbs&max-results=6"' type='text/javascript'/>
</b:loop>
<script defer='defer' type='text/javascript'>removeRelatedDuplicates_thumbs();printRelatedLabels_thumbs("<data:post.url/>");</script>
</div>
<div style='clear:both'/>
This code works fine except one problem. The code generates small images ( in default blogger thumbnail size which is s72-c) and there is no way to customize the size for (to change s72-c to s200/s200-c/w200).
I have found a image re-sizing solution script for Blogger but they are not helping. Here is it
function resizeThumb(size) {
var popularPost = document.getElementById('PopularPosts1');
var image = popularPost.getElementsByTagName('img');
for (var i = 0; i < image.length; i++) {
image[i].src = image[i].src.replace(/\/s72\-c/g, "\/s" + size + "-c")
}
}
resizeThumb(200);
This is for Popular post widget. And I know if I change the ID in the first line this will replace the image. But this is not solution but a cover up. And this also means the two images are loaded on is s72-c and the replaced one.
I want to integrate it (something like this) in the first related post script. I have tried hard with very very little knowledge of javascript I have but fail. So I signed up to stackoverflow and this is my question post.
Thank you in advance for trying to the help me.
function code for image size s200-c
function resizeThumb(size) {
var popularPost = document.getElementById('PopularPosts1');
var image = popularPost.getElementsByTagName('img');
for (var i = 0; i < image.length; i++) {
image[i].src = image[i].src.replace(/\/s200\-c/g, "\/s" + size + "-c")
}
}
resizeThumb(200);
function code for image size s200
function resizeThumb(size) {
var popularPost = document.getElementById('PopularPosts1');
var image = popularPost.getElementsByTagName('img');
for (var i = 0; i < image.length; i++) {
image[i].src = image[i].src.replace(/\/s200\/g, "\/s" + size + "")
}
}
resizeThumb(200);
first,add
var thumb = 200;
after
var thumburl = new Array();
then
add
thumburl[relatedTitlesNum] = thumburl[relatedTitlesNum].replace("/s72-c/","/s"+thumb+"/");
after
thumburl[relatedTitlesNum] = entry.media$thumbnail.url;
hope you like it

Bars not appearing on graph

This HTML and Javascript combined are supposed to form bars that are the height of the numbers entered in the prompt, relative to each other. The bars are not appearing when the numbers are entered. What do I need to fix in my code in order to make the bars appear?
"use strict";
window.onload=function()
{
var userValue;
var i;
var j;
var k;
var error;
var correct;
j = 0;
k = 0;
error = new Array(j);
correct = new Array(k);
userValue = window.prompt("Insert values separated by comma, whitespace, or both.");
userValue = packArray(trimElements(toArray(userValue, " ,")));
for(i = 0; i < userValue.length; i++)
{
if(isNumeric(userValue[i]) === false)
{
error[j] = userValue[i];
j = j + 1;
}
else
{
correct[k] = userValue[i];
k = k + 1;
}
}
if(error.length > 0)
{
window.alert("Error: " + error);
}
else
{
createGraph(userValue, document.getElementById("positiveQuadrant"));
}
};
function toArray(data, delimiters)
{
var locArray;
var result;
var i;
var dataArray;
var start;
locArray = findPositions(data, delimiters);
result = "";
i = 0;
if(data === null)
{
data = "";
}
else
{
result = result + data;
}
if(delimiters === null)
{
delimiters = "";
}
else
{
result = result + delimiters;
}
if(delimiters.length === 0)
{
delimiters = delimiters + " \t\r\n\f";
}
dataArray = new Array(locArray.length + 1);
start = 0;
while(i < dataArray.length)
{
dataArray[i] = data.substring(start, locArray[i]);
start = locArray[i] + 1;
i = i + 1;
}
return dataArray;
}
function findPositions(someString, lookForThis)
{
var i;
var result;
var count;
result = new Array(count);
i = 0;
count = 0;
while(i < someString.length)
{
if(lookForThis.indexOf(someString.charAt(i)) >= 0)
{
result[count] = someString.indexOf(lookForThis.charAt(i), (i + 1) - 1);
count = count + 1;
}
i = i + 1;
}
return result;
}
function trimElements(array)
{
var i;
var trimArray;
trimArray = new Array(array.length);
i = 0;
while(i < array.length)
{
trimArray[i] = trim(array[i]);
i = i + 1;
}
return trimArray;
}
function packArray(array)
{
var i;
var count;
var packedArray;
i = 0;
count = 0;
packedArray = new Array(count);
while(i < array.length)
{
if(array[i] !== null && array[i] !== "")
{
packedArray[count] = array[i];
count = count + 1;
}
i = i + 1;
}
return packedArray;
}
function convertToNumber(array)
{
var i;
var result;
i = 0;
result = "";
while(i < array.length)
{
if(isNumeric(array[i]) === true)
{
array[i] = Number(array[i]);
}
else
{
result = result + " " + array[i];
}
i = i + 1;
}
return trim(result);
}
function trim(data)
{
var start;
var whitespace;
var end;
var result;
if(typeof data==="string")
{
whitespace=" \n\r\t\f";
start=0;
}
else
{
result=data;
}
while((start<data.length)&&(whitespace.indexOf(data.charAt(start))))
{
start=start+1;
};
end=data.length-1;
while((end>=0)&&(whitespace.indexOf(data.charAt(end))))
{
end=end-1;
};
if(end<start)
{
result="";
}
else
{
result=data.substring(1+start,end);
}
return result;
};
function createHTMLElement(elementType, id, classInfo, content)
{
if(elementType===null)
{
elementType="";
};
trim(elementType);
if(id===null)
{
id="";
}
trim(id);
if(id.length>0)
{
id=" "+"id="+'"'+id+'"'+" ";
};
if(classInfo===null)
{
classInfo="";
}
trim(classInfo);
if(classInfo.length>0)
{
classInfo=" "+ "class="+'"'+classInfo+'"';
}
if(content===null)
{
content="";
};
trim(content);
return '<' +elementType +
id + classInfo +
'>' + content +
'</' + elementType + '>';
};
function isNumeric(data)
{
return isNaN(data);
};
function getRandomInteger(upperLimit)
{
return Math.floor(Math.random()*(upperLimit+1));
};
function getRandomRGB()
{
var blue;
var green;
var red;
red=getRandomInteger(255);
blue=getRandomInteger(255);
green=getRandomInteger(255);
return"rgb("+red+","+green+","+blue+")";
};
function createScaledArray(array, scaleFactor)
{
var i;
var scaledArray;
scaledArray = new Array(array.length);
for(i = 0; i < array.length; i++)
{
scaledArray[i] = (array[i] / scaleFactor);
}
return scaledArray;
}
function createGraph(array, quadReference)
{
var i;
var loc;
var scaleFactor;
var scaleArray;
var html;
var element;
var elementTop;
if(array.length > 0)
{
loc = 0;
for(i = 0; i < array.length; i++)
{
if(Number(array[i]) > Number(array[loc]))
{
loc = i;
}
}
scaleFactor = Math.abs(array[loc]);
scaleArray = createScaledArray(array, scaleFactor);
html = "";
for(i = 0; i < scaleArray.length; i++)
{
html = html + createHTMLElement("div", "columnContainer", "columnContainer", createHTMLElement("div", "coloredArea" + i, "coloredArea", createHTMLElement("div", "dataValue", "dataValue", array[i])));
}
quadReference.innerHTML = html;
for(i = 0; i < scaleArray.length; i++)
{
element = document.getElementById("coloredArea" + i);
elementTop = (100 - (scaleArray[i] * 100));
if(elementTop > 100)
{
elementTop = elementTop + (scaleArray[i] * 100);
}
element.style.top = elementTop + "%";
element.style.height = Math.abs(scaleArray[i] * 100) + "%";
element.style.backgroundColor = getRandomRGB();
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title> Graphing </title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
<script src="Graphing.js" type="text/javascript"></script>
<style type="text/css">
{
border : 0;
margin : 0;
padding : 0;
}
body
{
font-family : "Times New Roman", serif;
font-size : 12pt;
}
.positiveQuadrant
{
height:12em;
width:2em;
border-right:solid black 3px;
}
.negativeQuadrant
{
position:relative;
height:2em;
width:22em;
border-top:solid black 3px;
bottom:2em;
}
.columnContainer
{
position: relative;
float: left;
height: 10em;
width: 1.5em;
margin: 1px;
}
.coloredArea
{
position: relative;
background-color: red;
}
.dataValue
{
font-size: 12pt;
text-align: center;
position: relative;
top: -16px;
}
</style>
</head>
<body>
<div class ="positiveQuadrant" id="positiveQuadrant"></div>
<div class = "negativeQuadrant" id ="negativeQuadrant"></div>
</body>
</html>

Categories