How to create substrings, replacing substrings? - javascript

With the following code I turn a string:
1Z3245799938735257
into:
1Z›324579š99›38735257
But now, I want to split the areas, between "›" and "š" and between "›" and the end of that string, into pairs.
So that the sub result is:
1Z›32,45,79š99›38,73,52,57
Now I want to change the pairs into String.fromCharCode(pair+32)
So that the sub result is:
1Z›#,M,oš99›F,i,T,Y
Replacing the "," with ""
So that the ultimate result is
1Z›#Moš99›FiTY
How can I do this?
var chars = new Array();
chars["00"] = " "; chars["01"] = "!"; chars["02"] = "“"; chars["03"] = "#"; chars["04"] = "$";
chars["05"] = "%"; chars["06"] = "&"; chars["07"] = "’"; chars["08"] = "("; chars["09"] = ")";
chars["10"] = "*"; chars["11"] = "+"; chars["12"] = ","; chars["13"] = "-"; chars["14"] = ".";
chars["15"] = "/"; chars["16"] = "0"; chars["17"] = "1"; chars["18"] = "2"; chars["19"] = "3";
chars["20"] = "4"; chars["21"] = "5"; chars["22"] = "6"; chars["23"] = "7"; chars["24"] = "8";
chars["25"] = "9"; chars["26"] = ":"; chars["27"] = ";"; chars["28"] = "<"; chars["29"] = "=";
chars["30"] = ">"; chars["31"] = "?"; chars["32"] = "#"; chars["33"] = "A"; chars["34"] = "B";
chars["35"] = "C"; chars["36"] = "D"; chars["37"] = "E"; chars["38"] = "F"; chars["39"] = "G";
chars["40"] = "H"; chars["41"] = "I"; chars["42"] = "J"; chars["43"] = "K"; chars["44"] = "L";
chars["45"] = "M"; chars["46"] = "N"; chars["47"] = "O"; chars["48"] = "P"; chars["49"] = "Q";
chars["50"] = "R"; chars["51"] = "S"; chars["52"] = "T"; chars["53"] = "U"; chars["54"] = "V";
chars["55"] = "W"; chars["56"] = "X"; chars["57"] = "Y"; chars["58"] = "Z"; chars["59"] = "[";
chars["60"] = "\\"; chars["61"] = "]"; chars["62"] = "^"; chars["63"] = "_"; chars["64"] = "`";
chars["65"] = "a"; chars["66"] = "b"; chars["67"] = "c"; chars["68"] = "d"; chars["69"] = "e";
chars["70"] = "f"; chars["71"] = "g"; chars["72"] = "h"; chars["73"] = "i"; chars["74"] = "j";
chars["75"] = "k"; chars["76"] = "l"; chars["77"] = "m"; chars["78"] = "n"; chars["79"] = "o";
chars["80"] = "p"; chars["81"] = "q"; chars["82"] = "r"; chars["83"] = "s"; chars["84"] = "t";
chars["85"] = "u"; chars["86"] = "v"; chars["87"] = "w"; chars["88"] = "x"; chars["89"] = "y";
chars["90"] = "z"; chars["91"] = "{"; chars["92"] = "|"; chars["93"] = "}"; chars["94"] = "~";
var charsv = new Array();
charsv[" "] = 128; charsv["!"] = 01; charsv['"'] = 02; charsv["#"] = 03; charsv["$"] = 04;
charsv["%"] = 05; charsv["&"] = 06; charsv["’"] = 07; charsv["("] = 08; charsv[")"] = 09;
charsv["*"] = 10; charsv["+"] = 11; charsv[","] = 12; charsv["-"] = 13; charsv["."] = 14;
charsv["/"] = 15; charsv["0"] = 16; charsv["1"] = 17; charsv["2"] = 18; charsv["3"] = 19;
charsv["4"] = 20; charsv["5"] = 21; charsv["6"] = 22; charsv["7"] = 23; charsv["8"] = 24;
charsv["9"] = 25; charsv[":"] = 26; charsv[";"] = 27; charsv["<"] = 28; charsv["="] = 29;
charsv[">"] = 30; charsv["?"] = 31; charsv["#"] = 32; charsv["A"] = 33; charsv["B"] = 34;
charsv["C"] = 35; charsv["D"] = 36; charsv["E"] = 37; charsv["F"] = 38; charsv["G"] = 39;
charsv["H"] = 40; charsv["I"] = 41; charsv["J"] = 42; charsv["K"] = 43; charsv["L"] = 44;
charsv["M"] = 45; charsv["N"] = 46; charsv["O"] = 47; charsv["P"] = 48; charsv["Q"] = 49;
charsv["R"] = 50; charsv["S"] = 51; charsv["T"] = 52; charsv["U"] = 53; charsv["V"] = 54;
charsv["W"] = 55; charsv["X"] = 56; charsv["Y"] = 57; charsv["Z"] = 58; charsv["["] = 59;
charsv["\\"] = 60; charsv["]"] = 61; charsv["^"] = 62; charsv["_"] = 63; charsv["`"] = 64;
charsv["a"] = 65; charsv["b"] = 66; charsv["c"] = 67; charsv["d"] = 68; charsv["e"] = 69;
charsv["f"] = 70; charsv["g"] = 71; charsv["h"] = 72; charsv["i"] = 73; charsv["j"] = 74;
charsv["k"] = 75; charsv["l"] = 76; charsv["m"] = 77; charsv["n"] = 78; charsv["o"] = 79;
charsv["p"] = 80; charsv["q"] = 81; charsv["r"] = 82; charsv["s"] = 83; charsv["t"] = 84;
charsv["u"] = 85; charsv["v"] = 86; charsv["w"] = 87; charsv["x"] = 88; charsv["y"] = 89;
charsv["z"] = 90; charsv["{"] = 91; charsv["|"] = 92; charsv["}"] = 93; charsv["~"] = 94;
charsv["š"] = 104; charsv["›"] = 105; charsv["œ"] = 106;
var x = this.getField("S1").valueAsString;
var out = this.getField("B1");
var m = 0;
var transformedString = x.replace(/[A-Z0-9]{2}/g, function(a) {
if (isNaN(a)) {
if (m > 0)
a = 'š' + a;
m = -1;
} else {
if (parseInt(a) > 94) {
if (m != 0)
a = 'š' + a;
m = 2;
} else {
a = String.fromCharCode(parseInt(a) + 32);
if (m == 2 || m == -1)
a = '›' + a;
m = 1;
}
}
return a;
});
transformedString = transformedString;
out.value = transformedString;
thank you so far.
But now comes the last few steps:
first: get the values from every single char from the array "charsv".
second: sum of char-values: (104*1)+(char-value1*1)+(char-value2*2)+(char-value3*3) and so on.
third: get the modulo of the sum. (sum of char-values % 103).
fourth: get the char of this value from the array "chars". if " ", replace with "€".
fifth: add "š" at the beginning from "transformedString" add the char from fourth and an "œ" at the end of "transformedString".

jsfiddle (adaptation of my answer to How to split and rebuild a string?)
var m = 0; // 0 = init, -1 = alpha-num, 1 = numeric < 95, 2 = numeric > 94
var transformedString = "1Z3245799938735257".replace(/[A-Z0-9]{2}/g, function(a) {
if (isNaN(a)) {
if (m > 0)
a = 'š' + a;
m = -1;
} else {
if (parseInt(a) > 94) {
if (m != 0)
a = 'š' + a;
m = 2;
} else {
a = String.fromCharCode(parseInt(a) + 32); // the only additional line
if (m == 2 || m == -1)
a = '>' + a;
m = 1;
}
}
return a;
});

function convert(x) {
return x.replace(/›[^š]*/g, function (y) {
var s = "›";
for (var i = 1; i < y.length; i += 2) {
var code = parseInt(y.substring(i, i + 2));
s += String.fromCharCode(code + 32);
}
return s;
});
}
var result = convert("1Z›324579š99›38735257"); // 1Z›#Moš99›FiTY

Here is my attempt, might be a little much.
function transform(str) {
return str.replace(/›[^š]+/g, function(m) {
m = m.slice(1).replace(/../g, function(c) {
return String.fromCharCode(parseInt(c) + 32)
})
return '›' + m
});
}
var result = transform('1Z›324579š99›38735257') // 1Z›#Moš99›FiTY

I think you can use a regex like this:
/(\d{2})(?=\d+)/g
With substitution $1,.
[Regex Demo]

Related

JavaScript Functions: Grade Distributions

I was wondering if someone could help me understand what I am doing wrong? Below I have posted the assignment question, my code, and then the result I am getting.
Assignment
Here is my code:
function parseScores(scoresString) {
// TODO: Compete the function
let inString = scoresString.split();
return inString;
}
function buildDistributionArray(scoresArray) {
// TODO: Compete the function
let x = 0;
let distributeArray = new Array(5);
distributeArray[0] = 0;
distributeArray1 = 0;
distributeArray2 = 0;
distributeArray3 = 0;
distributeArray[4] = 0;
for(i = 0; i < scoresArray.length; i++){
if(scoresArray[i] >= 90){
distributeArray[0]++;
}
else if(scoresArray[i] >= 80 && scoresArray[i] <= 89){
distributeArray[1]++;
}
else if (scoresArray[i] >= 70 && scoresArray[i] <= 79) {
distributeArray[2]++;
}
else if(scoresArray[i] >= 60 && scoresArray[i] <= 69){
distributeArray[3]++;
}
else if(scoresArray[i] <= 59 && scoresArray[i] >= 0) {
distributeArray[4]++;
}
return distributeArray;
}
}
function setTableContent(userInput) {
// TODO: Compete the function
let myTable = document.getElementById("distributionTable");
if(userInput.length > 0) {
let parsedScores = parseScores(userInput);
let buildArray = buildDistributionArray(parsedScores);
let row = myTable.insertRow(0);
let row2 = myTable.insertRow(1);
let row3 = myTable.insertRow(2);
let cell1 = row2.insertCell(0);
let cell2 = row2.insertCell(1);
let cell3 = row2.insertCell(2);
let cell4 = row2.insertCell(3);
let cell5 = row2.insertCell(4);
cell1.innerHTML = "A";
cell2.innerHTML = "B";
cell3.innerHTML = "C";
cell4.innerHTML = "D";
cell5.innerHTML = "F";
let graphValueArray = [];
let occuranceArray = [];
for(index = 0; index < 5; index++){
occuranceArray[index] = row3.insertCell(index);
occuranceArray[index].innerHTML = buildArray[index];
graphValueArray[index] = row.insertCell(index);
let styleClass = "bar" + index;
let heightValue = (buildArray[index] * 10) + "px";
graphValueArray[index].innerHTML = "<div style = 'height" + heightValue + "class = " + styleClass + "></div>";
}
}
else {
let emptyRow = myTable.insertRow(0);
let emptyCell = emptyRow.insertCell(0);
emptyCell.innerHTML = "No graph to display";
}
}
// The argument can be changed for testing purposes
setTableContent("45 78 98 83 86 99 90 59");
my results:
Result
Here is my HTML
HTML
The problem is where you do .split(). You have to split it on space, so .split(' ')
Another tip, you don't need to include the upper limit in the if statements. The previous if statement takes care of it.
See if this works:
function parseScores(scoresString) {
// TODO: Complete the function
let inString = scoresString.split(' ');
return inString;
}
function buildDistributionArray(scoresArray) {
// TODO: Compete the function
let x = 0;
let distributeArray = new Array();
distributeArray[0] = 0;
distributeArray[1] = 0;
distributeArray[2] = 0;
distributeArray[3] = 0;
distributeArray[4] = 0;
for(i = 0; i < scoresArray.length; i++){
if (scoresArray[i] >= 90){
distributeArray[0]++;
}
else if (scoresArray[i] >= 80){
distributeArray[1]++;
}
else if (scoresArray[i] >= 70) {
distributeArray[2]++;
}
else if(scoresArray[i] >= 60){
distributeArray[3]++;
}
else if(scoresArray[i] <= 59 && scoresArray[i] >= 0) {
distributeArray[4]++;
}
return distributeArray;
}
}
function setTableContent(userInput) {
// TODO: Compete the function
let myTable = document.getElementById("distributionTable");
if(userInput.length > 0) {
let parsedScores = parseScores(userInput);
let buildArray = buildDistributionArray(parsedScores);
let row = myTable.insertRow(0);
let row2 = myTable.insertRow(1);
let row3 = myTable.insertRow(2);
let cell1 = row2.insertCell(0);
let cell2 = row2.insertCell(1);
let cell3 = row2.insertCell(2);
let cell4 = row2.insertCell(3);
let cell5 = row2.insertCell(4);
cell1.innerHTML = "A";
cell2.innerHTML = "B";
cell3.innerHTML = "C";
cell4.innerHTML = "D";
cell5.innerHTML = "F";
let graphValueArray = [];
let occuranceArray = [];
for(index = 0; index < 5; index++){
occuranceArray[index] = row3.insertCell(index);
occuranceArray[index].innerHTML = buildArray[index];
graphValueArray[index] = row.insertCell(index);
let styleClass = "bar" + index;
let heightValue = (buildArray[index] * 10) + "px";
graphValueArray[index].innerHTML = "<div style = 'height" + heightValue + "class = " + styleClass + "></div>";
}
}
else {
let emptyRow = myTable.insertRow(0);
let emptyCell = emptyRow.insertCell(0);
emptyCell.innerHTML = "No graph to display";
}
}
// The argument can be changed for testing purposes
setTableContent("45 78 98 83 86 99 90 59");

Converting text to small number javascript

I am trying to make a real time chat system. I am sending messages and saving them to the database. But before saving the message into database i need to encrypt it with using NTRU for Integers algorithm. In order to use this algorithm i have to convert text into numbers. I already tried to convert to ASCII code but its creating too big number for algorithm. Is there any way to convert text into small numbers? Saving into database with parent.send_message(chat_input.value)
create_chat(){
var parent = this;
var title_container = document.getElementById('title_container')
var title = document.getElementById('title')
title_container.classList.add('chat_title_container')
title.classList.add('chat_title')
var chat_container = document.createElement('div')
chat_container.setAttribute('id', 'chat_container')
var chat_inner_container = document.createElement('div')
chat_inner_container.setAttribute('id', 'chat_inner_container')
var chat_content_container = document.createElement('div')
chat_content_container.setAttribute('id', 'chat_content_container')
var chat_input_container = document.createElement('div')
chat_input_container.setAttribute('id', 'chat_input_container')
var chat_input_send = document.createElement('button')
chat_input_send.setAttribute('id', 'chat_input_send')
chat_input_send.setAttribute('disabled', true)
chat_input_send.innerHTML = `<i class="far fa-paper-plane"></i>`
var chat_input = document.createElement('input')
chat_input.setAttribute('id', 'chat_input')
chat_input.setAttribute('maxlength', 11)
chat_input.placeholder = `${parent.get_name()}. Say hello..`
chat_input.onkeyup = function(){
if(chat_input.value.length > 0){
chat_input_send.removeAttribute('disabled')
chat_input_send.classList.add('enabled')
chat_input_send.onclick = function(){
chat_input_send.setAttribute('disabled', true)
chat_input_send.classList.remove('enabled')
if(chat_input.value.length <= 0){
return
}
parent.create_load('chat_content_container')
chat_input.value = chat_input.value.toLocaleUpperCase()
parent.send_message(chat_input.value)
chat_input.value = ''
chat_input.focus()
}
I was able to solve my problem with this code
// Vocabulary
let vocabulary = new Array();{
vocabulary[10] = "A";
vocabulary[11] = "B";
vocabulary[12] = "C";
vocabulary[13] = "D";
vocabulary[14] = "E";
vocabulary[15] = "F";
vocabulary[16] = "G";
vocabulary[17] = "H";
vocabulary[18] = "I";
vocabulary[19] = "J";
vocabulary[20] = "K";
vocabulary[21] = "L";
vocabulary[22] = "M";
vocabulary[23] = "N";
vocabulary[24] = "O";
vocabulary[25] = "P";
vocabulary[26] = "Q";
vocabulary[27] = "R";
vocabulary[28] = "S";
vocabulary[29] = "T";
vocabulary[30] = "U";
vocabulary[31] = "V";
vocabulary[32] = "W";
vocabulary[33] = "X";
vocabulary[34] = "Y";
vocabulary[35] = "Z";
vocabulary[36] = " ";
vocabulary[37] = "a";
vocabulary[38] = "b";
vocabulary[39] = "c";
vocabulary[40] = "d";
vocabulary[41] = "e";
vocabulary[42] = "f";
vocabulary[43] = "g";
vocabulary[44] = "h";
vocabulary[45] = "i";
vocabulary[46] = "j";
vocabulary[47] = "k";
vocabulary[48] = "l";
vocabulary[49] = "m";
vocabulary[50] = "n";
vocabulary[51] = "o";
vocabulary[52] = "p";
vocabulary[53] = "q";
vocabulary[54] = "r";
vocabulary[55] = "s";
vocabulary[56] = "t";
vocabulary[57] = "u";
vocabulary[58] = "v";
vocabulary[59] = "w";
vocabulary[60] = "x";
vocabulary[61] = "y";
vocabulary[62] = "z";
vocabulary[63] = "!";
}
// Converting Text into numbers
var number = "";
for(var z = 0 ; z < chat_input.value.length ; z++)
{
for(var i = 10 ; i < 64 ; i++) {
if(chat_input.value.charAt(z) == vocabulary[i]) {
var test = i;
test = test.toString();
number = number + test;
}
}
}
// Seperating numbers into array
var numbers = new Array() ;
var index = 0 ;
while(number.length !== 0) {
if (number.length == 3) {
numbers[index] = number.substring(0, 3);
number = number.substring(3,number.length);
} else if (number.length == 2) {
numbers[index] = number.substring(0, 2);
number = number.substring(2,number.length);
} else if (number.length == 1) {
numbers[index] = number.substring(0, 1);
number = number.substring(1,number.length);
} else
numbers[index] = number.substring(0, 4);
number = number.substring(4,number.length);
index++;
}
//Encrpyting numbers and getting cipher text
var indexofe = 0 ;
var ciphertextz = new Array();
while(indexofe !== numbers.length) {
ciphertextz[indexofe] = parent.Encrypt(numbers[indexofe]);
indexofe++;
}

How to center scaling of game world in Create.js?

I am creating a Create.js 2D game engine in JavaScript and need a way to center the player (which will be a sprite placed in the center of the screen) when the main container is scaled. It should be an offset to the containers translation every time the world is scaled, but I can't figure out how to do the calculation so I have put a ?? and comments where I need help with the code. How do I figure out how much to translate the container to the center when it is scaled? Code below.
var stage;
var canvas;
var map;
var move = [];
var viewDist = 2;
var chunkSize = 16;
var mapSize = 32;
var view_chunks = [];
var chunks = [];
var posX;
var posY;
var tileSize = 16;
var chunksContainer;
var playerPosX = 0;
var playerPosY = 0;
var chunkPosX = 0;
var chunkPosY = 0;
var scale = 3;
var SPRITESHEET;
var tiles = [];
var speed = 0.2;
var moveForward = false;
var moveBackward = false;
var chunksContainer = new createjs.Container();
var halfW = window.innerWidth/2
var halfH = window.innerHeight/2
var scaleFactor = 0.1;
this.document.onkeydown = keydown;
function keydown(event) {
/** you can access keyCode to determine which key was pressed**/
var keyCode = event.keyCode;
if(keyCode == 87){
move[0] = true;
}
if(keyCode == 83){
move[1] = true;
}
if(keyCode == 65){
move[2] = true;
}
if(keyCode == 68){
move[3] = true;
}
if(keyCode == 187){
if(scale < 4){
scale = scale + 0.1;
}
}
if(keyCode == 189){
if(scale > ((viewDist*2+5)*chunkSize*tileSize)/window.innerWidth){
scale = scale - 0.1;
//chunksContainer.x = chunksContainer.x ??
//chunksContainer.y = chunksContainer.y ??
}
console.log(scale)
}
//console.log(keyCode)
}
this.document.onkeyup = keyup;
function keyup(event) {
/** you can access keyCode to determine which key was pressed**/
var keyCode = event.keyCode;
if(keyCode == 87){
move[0] = false;
}
if(keyCode == 83){
move[1] = false;
}
if(keyCode == 65){
move[2] = false;
}
if(keyCode == 68){
move[3] = false;
}
console.log(event.keyCode)
}
function generateMap() {
map = [];
for(var x = 0; x < mapSize*chunkSize; x++){
map[x] = []
for(var y = 0; y < mapSize*chunkSize; y++){
map[x][y] = 5;
if(Math.floor(Math.random() * 11) == 1){
map[x][y] = 1;
}
}
}
}
function getTile(col,row,x,y){
col = col%mapSize;
row = row%mapSize;
if(col < 0){
col = mapSize + col;
}
if(row < 0){
row = mapSize + row;
}
col = Math.abs(col);
row = Math.abs(row);
return map[col*chunkSize + x][row*chunkSize+y]
}
function init(){
canvas = document.getElementById("canvas");
canvas.width = document.body.clientWidth; //document.width is obsolete
canvas.height = document.body.clientHeight; //document.height is obsolete
// create a new stage and point it at our canvas:
stage = new createjs.Stage("canvas");
// load the spritesheet image:
var image = new Image();
image.onload = handleLoad;
image.src = "../assets/spritesheet/roguelikeSheet_transparent.png";
}
var tiles;
function generateChunks(x,y){
chunksContainer = new createjs.Container();
chunksContainer.scale = scale;
chunksContainer.x = 0
chunksContainer.y = 0
chunksContainer.regX = (viewDist*2)*chunkSize*tileSize/2
chunksContainer.regY = (viewDist*2)*chunkSize*tileSize/2
for(col = 0; col < viewDist*2; col++){
tiles[col] = []
for(row = 0; row < viewDist*2; row++){
tiles[col][row] = []
for (var x=0; x<chunkSize; x++) {
tiles[col][row][x] = []
for (var y=0; y<chunkSize; y++) {
var idx = getTile(chunkPosX + col,chunkPosY + row,x,y);
tiles[col][row][x][y] = new createjs.Sprite(SPRITESHEET)
.set({x: 16*(col * 16 + x), y:16*(row * 16 + y)});
tiles[col][row][x][y].gotoAndStop(idx);
chunksContainer.addChild(tiles[col][row][x][y]);
}
}
}
}
stage.addChild(chunksContainer);
}
function updateChunks(){
for(col = 0; col < viewDist*2; col++){
for(row = 0; row < viewDist*2; row++){
for (var x=0; x<chunkSize; x++) {
for (var y=0; y<chunkSize; y++) {
var idx = getTile(chunkPosX + col,chunkPosY + row,x,y);
tiles[col][row][x][y].gotoAndStop(idx);
}
}
}
}
}
function handleLoad(evt) {
// define the spritesheet:
SPRITESHEET = new createjs.SpriteSheet({
images: [evt.target],
frames: {width:16, height:16, regX:16, regY:16, spacing:1, margin:0, count:1680}
});
generateMap();
generateChunks();
stage.update();
// update the stage to draw to screen:
createjs.Ticker.addEventListener("tick", handleTick);
}
chunkPlayerPosY = 0;
chunkPlayerPosX = 0;
function handleTick(event) {
if(move[0]){
chunksContainer.y = chunksContainer.y + speed * createjs.Ticker.getMeasuredTickTime() * scale;
}
if(move[1]){
chunksContainer.y = chunksContainer.y - speed * createjs.Ticker.getMeasuredTickTime() * scale;
}
if(move[2]){
chunksContainer.x = chunksContainer.x + speed * createjs.Ticker.getMeasuredTickTime() * scale;
}
if(move[3]){
chunksContainer.x = chunksContainer.x - speed * createjs.Ticker.getMeasuredTickTime() * scale;
}
if(chunksContainer.y > halfH + chunkSize*tileSize * scale){
chunksContainer.y = halfH;
chunkPosY = chunkPosY - 1
console.log(chunkPosY)
updateChunks();
}
if(chunksContainer.y < halfH){
chunksContainer.y = halfH + chunkSize*tileSize * scale;
chunkPosY = chunkPosY + 1
console.log(chunkPosY)
updateChunks();
}
if(chunksContainer.x > halfW + chunkSize*tileSize * scale){
chunksContainer.x = halfW;
chunkPosX = chunkPosX - 1
console.log(chunkPosX)
updateChunks();
}
if(chunksContainer.x < halfW){
chunksContainer.x = halfW + chunkSize * tileSize * scale;
chunkPosX = chunkPosX + 1
console.log(chunkPosX)
updateChunks();
}
chunksContainer.scale = scale;
stage.update();
}

There's an odd infinite scroll on my website after adding some JavaScript to the pages

I've added some JavaScript to my website that adds a glitter effect following the mouse as you move it and I absolutely love it. Except the fact that about halfway down the page a random new scroll bar appears and it scrolls past the footer and on forever. I can't seem to figure out what to add, or take out to make it stop scrolling past the footer. I've tried setting a max height for the body/html... I've tried taking out the "set scroll" function, I need it to stop scrolling on forever. I've also tried adding in the finish() method but I'm not exactly sure where it goes. Here is my code.
var colour = "#ffffff";
var sparkles = 200;
var x = ox = 400;
var y = oy = 300;
var swide = 800;
var shigh = 600;
var sleft = sdown = 0;
var tiny = new Array();
var star = new Array();
var starv = new Array();
var starx = new Array();
var stary = new Array();
var tinyx = new Array();
var tinyy = new Array();
var tinyv = new Array();
colours = new Array('#ffffff', '#cbaa89')
n = 10;
y = 0;
x = 0;
n6 = (document.getElementById && !document.all);
ns = (document.layers);
ie = (document.all);
d = (ns || ie) ? 'document.' : 'document.getElementById("';
a = (ns || n6) ? '' : 'all.';
n6r = (n6) ? '")' : '';
s = (ns) ? '' : '.style';
if (ns) {
for (i = 0; i < n; i++)
document.write('<layer name="dots' + i + '" top=0 left=0 width=' + i / 2 + ' height=' + i / 2 + ' bgcolor=#ff0000></layer>');
}
if (ie)
document.write('<div id="con" style="position:absolute;top:0px;left:0px"><div style="position:relative">');
if (ie || n6) {
for (i = 0; i < n; i++)
document.write('<div id="dots' + i + '" style="position:absolute;top:0px;left:0px;width:' + i / 2 + 'px;height:' + i / 2 + 'px;background:#ff0000;font-size:' + i / 2 + '"></div>');
}
if (ie)
document.write('</div></div>');
(ns || n6) ? window.captureEvents(Event.MOUSEMOVE): 0;
function Mouse(evnt) {
y = (ns || n6) ? evnt.pageY + 4 - window.pageYOffset : event.y + 4;
x = (ns || n6) ? evnt.pageX + 1 : event.x + 1;
}
(ns) ? window.onMouseMove = Mouse: document.onmousemove = Mouse;
function animate() {
o = (ns || n6) ? window.pageYOffset : 0;
if (ie) con.style.top = document.body.scrollTop + 'px';
for (i = 0; i < n; i++) {
var temp1 = eval(d + a + "dots" + i + n6r + s);
randcolours = colours[Math.floor(Math.random() * colours.length)];
(ns) ? temp1.bgColor = randcolours: temp1.background = randcolours;
if (i < n - 1) {
var temp2 = eval(d + a + "dots" + (i + 1) + n6r + s);
temp1.top = parseInt(temp2.top) + 'px';
temp1.left = parseInt(temp2.left) + 'px';
} else {
temp1.top = y + o + 'px';
temp1.left = x + 'px';
}
}
setTimeout("animate()", 10);
}
animate();
window.onload = function() {
if (document.getElementById) {
var i, rats, rlef, rdow;
for (var i = 0; i < sparkles; i++) {
var rats = createDiv(3, 3);
rats.style.visibility = "hidden";
rats.style.zIndex = "999";
document.body.appendChild(tiny[i] = rats);
starv[i] = 0;
tinyv[i] = 0;
var rats = createDiv(5, 5);
rats.style.backgroundColor = "transparent";
rats.style.visibility = "hidden";
rats.style.zIndex = "999";
var rlef = createDiv(1, 5);
var rdow = createDiv(5, 1);
rats.appendChild(rlef);
rats.appendChild(rdow);
rlef.style.top = "2px";
rlef.style.left = "0px";
rdow.style.top = "0px";
rdow.style.left = "2px";
document.body.appendChild(star[i] = rats);
}
set_width();
sparkle();
}
}
function sparkle() {
var c;
if (Math.abs(x - ox) > 1 || Math.abs(y - oy) > 1) {
ox = x;
oy = y;
for (c = 0; c < sparkles; c++)
if (!starv[c]) {
star[c].style.left = (starx[c] = x) + "px";
star[c].style.top = (stary[c] = y + 1) + "px";
star[c].style.clip = "rect(0px, 5px, 5px, 0px)";
star[c].childNodes[0].style.backgroundColor = star[c].childNodes[1].style.backgroundColor = (colour == "random") ? newColour() : colour;
star[c].style.visibility = "visible";
starv[c] = 50;
break;
}
}
for (c = 0; c < sparkles; c++) {
if (starv[c]) update_star(c);
if (tinyv[c]) update_tiny(c);
}
setTimeout("sparkle()", 40);
}
function update_star(i) {
if (--starv[i] == 25) star[i].style.clip = "rect(1px, 4px, 4px, 1px)";
if (starv[i]) {
stary[i] += 1 + Math.random() * 3;
starx[i] += (i % 5 - 2) / 5;
if (stary[i] < shigh + sdown) {
star[i].style.top = stary[i] + "px";
star[i].style.left = starx[i] + "px";
} else {
star[i].style.visibility = "hidden";
starv[i] = 0;
return;
}
} else {
tinyv[i] = 50;
tiny[i].style.top = (tinyy[i] = stary[i]) + "px";
tiny[i].style.left = (tinyx[i] = starx[i]) + "px";
tiny[i].style.width = "2px";
tiny[i].style.height = "2px";
tiny[i].style.backgroundColor = star[i].childNodes[0].style.backgroundColor;
star[i].style.visibility = "hidden";
tiny[i].style.visibility = "visible"
}
}
function update_tiny(i) {
if (--tinyv[i] == 25) {
tiny[i].style.width = "1px";
tiny[i].style.height = "1px";
}
if (tinyv[i]) {
tinyy[i] += 1 + Math.random() * 3;
tinyx[i] += (i % 5 - 2) / 5;
if (tinyy[i] < shigh + sdown) {
tiny[i].style.top = tinyy[i] + "px";
tiny[i].style.left = tinyx[i] + "px";
} else {
tiny[i].style.visibility = "hidden";
tinyv[i] = 0;
return;
}
} else tiny[i].style.visibility = "hidden";
}
document.onmousemove = mouse;
function mouse(e) {
if (e) {
y = e.pageY;
x = e.pageX;
} else {
set_scroll();
y = event.y + sdown;
x = event.x + sleft;
}
}
window.onscroll = set_scroll;
function set_scroll() {
if (typeof(self.pageYOffset) == 'number') {
sdown = self.pageYOffset;
sleft = self.pageXOffset;
} else if (document.body && (document.body.scrollTop || document.body.scrollLeft)) {
sdown = document.body.scrollTop;
sleft = document.body.scrollLeft;
} else if (document.documentElement && (document.documentElement.scrollTop || document.documentElement.scrollLeft)) {
sleft = document.documentElement.scrollLeft;
sdown = document.documentElement.scrollTop;
} else {
sdown = 0;
sleft = 0;
}
}
window.onresize = set_width;
function set_width() {
var sw_min = 999999;
var sh_min = 999999;
if (document.documentElement && document.documentElement.clientWidth) {
if (document.documentElement.clientWidth > 0) sw_min = document.documentElement.clientWidth;
if (document.documentElement.clientHeight > 0) sh_min = document.documentElement.clientHeight;
}
if (typeof(self.innerWidth) == 'number' && self.innerWidth) {
if (self.innerWidth > 0 && self.innerWidth < sw_min) sw_min = self.innerWidth;
if (self.innerHeight > 0 && self.innerHeight < sh_min) sh_min = self.innerHeight;
}
if (document.body.clientWidth) {
if (document.body.clientWidth > 0 && document.body.clientWidth < sw_min) sw_min = document.body.clientWidth;
if (document.body.clientHeight > 0 && document.body.clientHeight < sh_min) sh_min = document.body.clientHeight;
}
if (sw_min == 999999 || sh_min == 999999) {
sw_min = 800;
sh_min = 600;
}
swide = sw_min;
shigh = sh_min;
}
function createDiv(height, width) {
var div = document.createElement("div");
div.style.position = "absolute";
div.style.height = height + "px";
div.style.width = width + "px";
div.style.overflow = "hidden";
return (div);
}
function newColour() {
var c = new Array();
c[0] = 255;
c[1] = Math.floor(Math.random() * 256);
c[2] = Math.floor(Math.random() * (256 - c[1] / 2));
c.sort(function() {
return (0.5 - Math.random());
});
return ("rgb(" + c[0] + ", " + c[1] + ", " + c[2] + ")");
}
I've also made a jsfiddle here https://jsfiddle.net/5ydty5p2/
it's the sparkles that are wrongly positioned. If you take a look at the inspector (F12 you'll see them animating). The calculated position is incorrected and since they're created directly in the body they make it grow, and grow...
Since the whole script is a hack you could further hack it with a max-height property on the body...
Having sparkless is nice but you should really look for an alternative, this piece of JS is awful. And there is no jquery involved here, it's merely divs following the mouse. You should look for a proper plugin.

How to use AJAX or JSON in this code?

I am creating a website application that allows users to select a seat, if it is not already reserved, and reserve it.
I have created a very round about way of getting the seats that are previously reserved using iFrames, however that was temporarily, now I need to make it secure and "proper javascript code" using proper practices. I have no clue what AJAX (or JSON) is, nor how to add it to this code, but it needs to get the file "seatsReserved"+this.id(that is the date)+"Que.html" and compare the string of previously reserved seats to see which class to make the element. If this is horrible, or if any of the other things could work better, I am open to criticism to everything. Thank you all!
Here is the javascript code:
A little side note, all of the if statements are due to different amount of seats in each row
<script>
var i = " 0 ";
var counter = 0;
var leng=0;
document.getElementById("Show1").addEventListener("click", changeDay);
document.getElementById("Show2").addEventListener("click", changeDay);
document.getElementById("Show3").addEventListener("click", changeDay);
function changeDay() {
var iFrame = document.getElementById("seatList");
iFrame.src = "seatsReserved" + this.id + "Que.html";
document.getElementById('date').innerHTML = this.id;
var seatsTaken = iFrame.contentWindow.document.body.innerHTML;
var k = 0;
let = 'a';
var lc = 0;
for (lc = 1; lc <= 14; lc++) {
if (lc == 1) {
leng = 28;
}
else if (lc == 2) {
leng = 29;
}
else if (lc == 3) {
leng = 32;
}
else if (lc == 4 || lc == 6 || lc == 12 || lc == 14) {
leng = 33;
}
else if (lc == 5 || lc == 13) {
leng = 34;
}
else if (lc == 8 || lc == 10) {
leng = 35;
}
else {
leng = 36;
}
for (k = 1; k <= leng; k++) {
if (seatsTaken.indexOf((" " +
let +k + " ")) <= -1) {
seat = document.getElementById(let +k);
seat.removeEventListener("click", selectedSeat);
}
else {
document.getElementById(let +k).className = "openseat";
document.getElementById(let +k).removeEventListener("click", doNothing);
}
}
let = String.fromCharCode(let.charCodeAt(0) + 1);
}
}
function loadChanges() {
var iFrame = document.getElementById("seatList");
var seatsTaken = iFrame.contentWindow.document.body.innerHTML;
var k = 0;
let = 'a';
var lc = 0;
var leng = 0;
for (lc = 1; lc <= 14; lc++) {
if (lc == 1) {
leng = 28;
}
else if (lc == 2) {
leng = 29;
}
else if (lc == 3) {
leng = 32;
}
else if (lc == 4 || lc == 6 || lc == 12 || lc == 14) {
leng = 33;
}
else if (lc == 5 || lc == 13) {
leng = 34;
}
else if (lc == 8 || lc == 10) {
leng = 35;
}
else {
leng = 36;
}
for (k = 1; k <= leng; k++) {
if (seatsTaken.indexOf((" " +
let +k + " ")) <= -1) {
seat = document.getElementById(let +k);
seat.addEventListener("click", selectedSeat);
seat.className = "openseat";
}
else {
document.getElementById(let +k).className = "notAvailible";
document.getElementById(let +k).addEventListener("click", doNothing);
}
}
let = String.fromCharCode(let.charCodeAt(0) + 1);
}
i = " 0 ";
counter = 0;
document.getElementById("seatString").innerHTML = i;
document.getElementById("getSeats").value = i;
document.getElementById("seatnums").innerHTML = counter;
}
i = document.getElementById("seatString").innerHTML;
counter = document.getElementById("seatnums").innerHTML;
function selectedSeat() {
var w = this.id;
var l = (" " + w);
var b = (" " + w + " ");
if (counter < 5) {
if (i.indexOf(b) <= 0) {
this.className = "closedseat";
i = i + b;
i = i.replace(" 0 ", " ");
document.getElementById("seatString").innerHTML = i;
document.getElementById("getSeats").value = i;
counter = counter + 1;
document.getElementById("seatnums").innerHTML = counter;
}
else if (i.indexOf(b) > 0) {
this.className = "openseat";
i = i.replace(b, "");
document.getElementById("seatString").innerHTML = i;
document.getElementById("getSeats").value = i;
counter = counter - 1;
document.getElementById("seatnums").innerHTML = counter;
}
}
else if (i.indexOf(b) > 0) {
this.className = "openseat";
i = i.replace(b, "");
document.getElementById("seatString").innerHTML = i;
document.getElementById("getSeats").value = i;
counter = counter - 1;
document.getElementById("seatnums").innerHTML = counter;
}
}
function doNothing() {
}
var rannum = Math.random() * 1000;
document.getElementById('getConfirmation').value = rannum;
</script>

Categories

Resources