javascript:window.print() not showing barcode for printing - javascript

I am making Mean Stack App in which I need to print barcode, I am using an angular js directive for generating code 128 barcode, and it is generating well, but when I click print button (javascript:window.print()) it is not showing the barcode in printing window neither in PDF,
Here is my directive,
.directive('barcodeGenerator', [function() {
var Barcode = (function () {
var barcode = {
settings: {
barWidth: 1,
barHeight: 50,
moduleSize: 5,
showHRI: false,
addQuietZone: true,
marginHRI: 5,
bgColor: "#FFFFFF",
color: "#000000",
fontSize: 10,
posX: 0,
posY: 0
},
intval: function(val) {
var type = typeof(val);
if ( type == 'string' ) {
val = val.replace(/[^0-9-.]/g, "");
val = parseInt(val * 1, 10);
return isNaN(val) || !isFinite(val)? 0: val;
}
return type == 'number' && isFinite(val)? Math.floor(val): 0;
},
code128: {
encoding:[
"11011001100", "11001101100", "11001100110", "10010011000",
"10010001100", "10001001100", "10011001000", "10011000100",
"10001100100", "11001001000", "11001000100", "11000100100",
"10110011100", "10011011100", "10011001110", "10111001100",
"10011101100", "10011100110", "11001110010", "11001011100",
"11001001110", "11011100100", "11001110100", "11101101110",
"11101001100", "11100101100", "11100100110", "11101100100",
"11100110100", "11100110010", "11011011000", "11011000110",
"11000110110", "10100011000", "10001011000", "10001000110",
"10110001000", "10001101000", "10001100010", "11010001000",
"11000101000", "11000100010", "10110111000", "10110001110",
"10001101110", "10111011000", "10111000110", "10001110110",
"11101110110", "11010001110", "11000101110", "11011101000",
"11011100010", "11011101110", "11101011000", "11101000110",
"11100010110", "11101101000", "11101100010", "11100011010",
"11101111010", "11001000010", "11110001010", "10100110000",
"10100001100", "10010110000", "10010000110", "10000101100",
"10000100110", "10110010000", "10110000100", "10011010000",
"10011000010", "10000110100", "10000110010", "11000010010",
"11001010000", "11110111010", "11000010100", "10001111010",
"10100111100", "10010111100", "10010011110", "10111100100",
"10011110100", "10011110010", "11110100100", "11110010100",
"11110010010", "11011011110", "11011110110", "11110110110",
"10101111000", "10100011110", "10001011110", "10111101000",
"10111100010", "11110101000", "11110100010", "10111011110",
"10111101110", "11101011110", "11110101110", "11010000100",
"11010010000", "11010011100", "11000111010"
],
getDigit: function(code) {
var tableB = " !\"#$%&'()*+,-./0123456789:;<=>?#ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
var result = "";
var sum = 0;
var isum = 0;
var i = 0;
var j = 0;
var value = 0;
// check each characters
for(i=0; i<code.length; i++){
if (tableB.indexOf(code.charAt(i)) == -1){
return("");
}
}
// check firsts characters : start with C table only if enought numeric
var tableCActivated = code.length > 1;
var c = '';
for (i=0; i<3 && i<code.length; i++) {
c = code.charAt(i);
tableCActivated &= c >= '0' && c <= '9';
}
sum = tableCActivated ? 105 : 104;
// start : [105] : C table or [104] : B table
result = this.encoding[ sum ];
i = 0;
while ( i < code.length ) {
if ( !tableCActivated) {
j = 0;
// check next character to activate C table if interresting
while ( (i + j < code.length) && (code.charAt(i+j) >= '0') && (code.charAt(i+j) <= '9') ) {
j++;
}
// 6 min everywhere or 4 mini at the end
tableCActivated = (j > 5) || ((i + j - 1 == code.length) && (j > 3));
if ( tableCActivated ){
result += this.encoding[ 99 ]; // C table
sum += ++isum * 99;
} // 2 min for table C so need table B
} else if ( (i == code.length) || (code.charAt(i) < '0') || (code.charAt(i) > '9') || (code.charAt(i+1) < '0') || (code.charAt(i+1) > '9') ) {
tableCActivated = false;
result += this.encoding[ 100 ]; // B table
sum += ++isum * 100;
}
if ( tableCActivated ) {
value = barcode.intval(code.charAt(i) + code.charAt(i+1)); // Add two characters (numeric)
i += 2;
} else {
value = tableB.indexOf( code.charAt(i) ); // Add one character
i += 1;
}
result += this.encoding[ value ];
sum += ++isum * value;
}
result += this.encoding[sum % 103];// Add CRC
result += this.encoding[106];// Stop
result += "11";// Termination bar
return(result);
}
},
bitStringTo2DArray: function( digit) {//convert a bit string to an array of array of bit char
var d = [];
d[0] = [];
for ( var i=0; i<digit.length; i++) {
d[0][i] = digit.charAt(i);
}
return(d);
},
digitToCssRenderer: function( $container, settings, digit, hri, mw, mh, type) {// css barcode renderer
var lines = digit.length;
var columns = digit[0].length;
var content = "";
var len, current;
var bar0 = "<div class='w w%s' ></div>";
var bar1 = "<div class='b b%s' ></div>";
for ( var y=0, x; y<lines; y++) {
len = 0;
current = digit[y][0];
for ( x=0; x<columns; x++){
if ( current == digit[y][x] ) {
len++;
} else {
content += (current == '0'? bar0: bar1).replace("%s", len * mw);
current = digit[y][x];
len=1;
}
}
if ( len > 0) {
content += (current == '0'? bar0: bar1).replace("%s", len * mw);
}
}
if ( settings.showHRI) {
content += "<div style=\"clear:both; width: 100%; background-color: " + settings.bgColor + "; color: " + settings.color + "; text-align: center; font-size: " + settings.fontSize + "px; margin-top: " + settings.marginHRI + "px;\">"+hri+"</div>";
}
var div = document.createElement('DIV');
div.innerHTML = content;
div.className = 'barcode '+ type +' clearfix-child';
return div;
},
digitToCss: function($container, settings, digit, hri, type) {// css 1D barcode renderer
var w = barcode.intval(settings.barWidth);
var h = barcode.intval(settings.barHeight);
return this.digitToCssRenderer($container, settings, this.bitStringTo2DArray(digit), hri, w, h, type);
}
};
var generate = function(datas, type, settings) {
var
digit = "",
hri = "",
code = "",
crc = true,
rect = false,
b2d = false
;
if ( typeof(datas) == "string") {
code = datas;
} else if (typeof(datas) == "object") {
code = typeof(datas.code) == "string" ? datas.code : "";
crc = typeof(datas.crc) != "undefined" ? datas.crc : true;
rect = typeof(datas.rect) != "undefined" ? datas.rect : false;
}
if (code == "") {
return(false);
}
if (typeof(settings) == "undefined") {
settings = [];
}
for( var name in barcode.settings) {
if ( settings[name] == undefined) {
settings[name] = barcode.settings[name];
}
}
switch (type) {
case "std25":
case "int25": {
digit = barcode.i25.getDigit(code, crc, type);
hri = barcode.i25.compute(code, crc, type);
break;
}
case "ean8":
case "ean13": {
digit = barcode.ean.getDigit(code, type);
hri = barcode.ean.compute(code, type);
break;
}
case "upc": {
digit = barcode.upc.getDigit(code);
hri = barcode.upc.compute(code);
break;
}
case "code11": {
digit = barcode.code11.getDigit(code);
hri = code;
break;
}
case "code39": {
digit = barcode.code39.getDigit(code);
hri = code;
break;
}
case "code93": {
digit = barcode.code93.getDigit(code, crc);
hri = code;
break;
}
case "code128": {
digit = barcode.code128.getDigit(code);
hri = code;
break;
}
case "codabar": {
digit = barcode.codabar.getDigit(code);
hri = code;
break;
}
case "msi": {
digit = barcode.msi.getDigit(code, crc);
hri = barcode.msi.compute(code, crc);
break;
}
case "datamatrix": {
digit = barcode.datamatrix.getDigit(code, rect);
hri = code;
b2d = true;
break;
}
}
if ( digit.length == 0) {
return this;
}
if ( !b2d && settings.addQuietZone) {
digit = "0000000000" + digit + "0000000000";
}
var fname = 'digitToCss' + (b2d ? '2D' : '');
return barcode[fname](this, settings, digit, hri, type);
};
return generate;
}());
return {
link: function(scope, element, attrs) {
attrs.$observe('barcodeGenerator', function(value){
var code = Barcode(value, "code128",{barWidth:2}),
code_wrapper = angular.element("<div class='barcode code128'></div>")
code_wrapper.append(code);
angular.element(element).html('').append(code_wrapper);
});
}
}
And here is barcode generating code,
<div ng-model='myInput' barcode-generator="{{myInput}}" style="height:208px;">
</div>
Here are the screenshots
It shows barcode on the page
But not shows up while printing

It's because some browsers has turned off rendering background-color in print mode by default. You won't force all users to mess up with browser settings, but you can replace background-color with border-width like this:
<style type="text/css" media="print">
.barcode.code128 > div.b {
border-style: solid !important;
border-color: #000000 !important;
}
.barcode.code128 .b1 {
width: 0px !important;
border-width: 0px 0px 0px 1px !important;
}
.barcode.code128 .b2 {
width: 0px !important;
border-width: 0px 0px 0px 2px !important;
}
.barcode.code128 .b3 {
width: 0px !important;
border-width: 0px 0px 0px 3px !important;
}
.barcode.code128 .b4 {
width: 0px !important;
border-width: 0px 0px 0px 4px !important;
}
.barcode.code128 .b5 {
width: 0px !important;
border-width: 0px 0px 0px 5px !important;
}
.barcode.code128 .b6 {
width: 0px !important;
border-width: 0px 0px 0px 6px !important;
}
.barcode.code128 .b7 {
width: 0px !important;
border-width: 0px 0px 0px 7px !important;
}
.barcode.code128 .b8 {
width: 0px !important;
border-width: 0px 0px 0px 8px !important;
}
.barcode.code128 .b9 {
width: 0px !important;
border-width: 0px 0px 0px 9px !important;
}
.barcode.code128 .b10 {
width: 0px !important;
border-width: 0px 0px 0px 10px !important;
}

Related

Matrix Shortest Path

I can move left, right, up, down - no diagonal movement is allowed.
Can only travel to cells that contain 1s, not 0s.
Start in upper left cell (0,0)
End in lower right cell (2,3)
Last cell is undefined, should be (2,3).
let visited = [[false, false, false, false],
[false, false, false, false],
[false, false, false, false]]
function shortestPath(arr, c, r) {
if (arr.length === c + 1 && arr[0].length === r + 1) {
if (arr[c][r] === 1) {
return true;
}
else { return false }
}
if (c === arr.length || r === arr[0].length || c < 0 || r < 0) { return }
console.log(r, c)
if (arr[c][r] === 0) { return }
if (visited[c][r]) { return }
visited[c][r] = true
shortestPath(arr, c, r + 1)
shortestPath(arr, c + 1, r)
shortestPath(arr, c, r - 1)
shortestPath(arr, c - 1, r)
}
let a = [[1, 1, 1, 0],
[1, 1, 0, 1],
[1, 1, 1, 1]]
console.log(shortestPath(a, 0, 0))
Output:
0 0
1 0
2 0
3 0
2 1
1 0
1 1
2 1
1 2
2 2
1 2
2 1
0 2
1 2
0 1
1 1
0 2
0 0
1 1
0 1
1 0
0 0
0 1
undefined
There you go:
https://jsfiddle.net/vanowm/j0dxqy7h/
function shortestPath(arr, start, end)
{
arr = arr.map(a => [...a]); //clone matrix, so we can re-use it by updating which coordinates we've visited
if (!start)
start = [0, 0];
if (!end)
end = [arr[0].length-1, arr.length-1];
arr[start[1]][start[0]] = 0; //set start position as unavailable
const paths = [[start]];
while (paths.length)
{
const path = paths.shift(), //remove first path out of all paths (we'll add it back to the end if it's not a dead end)
cur = path[path.length-1], //get last coordinates from the path
next = [ //next coordinates from current position
[cur[0], cur[1] + 1],
[cur[0] + 1, cur[1]],
[cur[0], cur[1] - 1],
[cur[0] - 1, cur[1]],
];
for (let i = 0, pos; i < next.length; i++)
{
pos = next[i];
if (pos[0] == end[0] && pos[1] == end[1])
return path.concat([end]); //found end position
if (pos[0] < 0 || pos[0] >= arr[0].length || //check boundaries for x
pos[1] < 0 || pos[1] >= arr.length || //check boundaries for y
!arr[pos[1]][pos[0]]) //position available?
{
continue;
}
arr[pos[1]][pos[0]] = 0; //mark position unavailable
paths.push(path.concat([pos])); //add position to the path
}
}
return [start]; //return start coordinates if no path found
}
showMatrix([
[1, 1, 1, 0],
[1, 1, 0, 1],
[1, 1, 1, 1]
]);
custom([
[1,1,0,1,1,1,1,0],
[1,0,1,1,0,0,1,1],
[1,0,1,0,1,1,0,1],
[1,0,1,1,0,1,1,1],
[1,0,0,1,0,1,0,0],
[1,1,0,1,0,1,1,1],
[1,0,1,1,1,0,0,1],
[1,1,0,0,1,0,1,1],
[0,1,1,1,1,0,1,1]
], [1,0],[6,7]);
function showMatrix(matrix, start, end, _box)
{
if (!start || start[0] >= matrix[0].length || start[1] >= matrix.length)
start = [0, 0];
if (!end || end[0] >= matrix[0].length || end[1] >= matrix.length)
end = [matrix[0].length-1, matrix.length-1];
const path = shortestPath(matrix, start, end);
console.log("matrix:", JSON.stringify(matrix));
console.log("path:", path.join("|"));
path.forEach(b => matrix[b[1]][b[0]] = 2); //merge path into matrix
matrix[start[1]][start[0]] = 3; //identify start
matrix[end[1]][end[0]] = 4; //identify end
let div = document.createElement("div");
const box = _box || div.cloneNode();
box.className = "matrix";
box.innerHTML = "";
box.style.gridTemplateColumns = "1fr ".repeat(matrix[0].length);
const pathPos = {};
path.forEach((a,i) => pathPos[a.join("x")] = i);
matrix.forEach((r, y) => r.forEach((t, x) =>
{
div = div.cloneNode(false);
div.className = "t" + t;
div.setAttribute("p", pathPos[x+"x"+y]!==undefined ? pathPos[x+"x"+y] : "");
div._xy = [x,y];
box.appendChild(div);
}));
if (!_box)
return document.body.appendChild(box);
box._matrix = matrix;
box._start = start;
box._end = end;
box.onmouseup = e =>
{
if (!e.target._xy)
return;
if (e.button)
{
if ((e.button == 2 && !(e.ctrlKey || e.shiftKey)) ||
(e.button != 2 && (e.ctrlKey || e.shiftKey)))
end = e.target._xy;
else
start = e.target._xy;
}
else
matrix[e.target._xy[1]][e.target._xy[0]] = ~~!matrix[e.target._xy[1]][e.target._xy[0]];
matrix = matrix.map(r => r.map(t => t ? 1 : 0));
showMatrix(matrix, start, end, box);
}
box.oncontextmenu = e => e.preventDefault();
}
function custom(matrix, start, end)
{
if (matrix)
{
document.getElementById("columns").value = matrix[0].length;
document.getElementById("rows").value = matrix.length;
}
const cols = ~~document.getElementById("columns").value,
rows = ~~document.getElementById("rows").value,
box = document.getElementById("custom");
if (start)
box._start = start;
if (end)
box._end = end;
matrix = matrix || box._matrix || [[]];
if (cols > matrix[0].length)
matrix.forEach((a,i) => matrix[i] = a.concat(Array(cols-a.length).fill(3)));
else if (cols < matrix[0].length)
matrix.forEach(a => a.splice(cols, a.length - cols));
if (rows > matrix.length)
matrix = matrix.concat([...Array(rows-matrix.length)].map(e => Array(cols).fill(1)));
else if (rows < matrix.length)
matrix.splice(rows, matrix.length - rows);
matrix = matrix.map(r => r.map(t => t ? 1 : 0));
showMatrix(matrix, box._start, box._end, box);
}
function random()
{
let matrix,
cols = ~~document.getElementById("columns").value,
rows = ~~document.getElementById("rows").value,
box = document.getElementById("custom"),
date = new Date();
do
{
matrix = [...Array(rows)].map(e => [...Array(cols)].map( e=> Math.round(Math.random()*1.4))); //generate less dense matrix
path = shortestPath(matrix, box._start, box._end);
}
while(path.length<2 && new Date - date < 10000) //10 sec max
matrix = matrix.map(r=>r.map(a=>Math.round(Math.random()*a*0.9))); //fake more density
path.forEach(a=>matrix[a[1]][a[0]]=1); //clear the path
custom(matrix);
}
.matrix:not(:empty)
{
display: inline-grid;
grid-gap: 1px;
border: 1px solid black;
margin: 0.5em;
width: fit-content;
}
.matrix *
{
width: 2em;
height: 2em;
background-color: grey;
outline: 1px solid black;
}
.matrix .t1
{
background-color: white;
}
.matrix .t2
{
background-color: lightgreen;
}
.matrix *:before
{
content: attr(p);
position: absolute;
width: 2em;
height: 2em;
line-height: 2em;
text-align: center;
font-size: 1em;
}
.matrix .t3
{
background-color: green;
}
.matrix .t4
{
background-color: red;
}
.custom .matrix
{
}
.custom .matrix :hover
{
opacity: 0.8;
box-shadow: 0 0 5px 1px black;
z-index: 1;
}
.custom .matrix :hover:after
{
content: "";
display: block;
width: 100%;
height: 100%;
box-shadow: 0 0 5px 1px black inset;
}
.custom .matrix .t1:hover
{
background-color: #CCC;
}
input
{
width: 3em;
}
.custom
{
display: inline-grid;
vertical-align: top;
padding: 0.5em;
padding-bottom: 3em;
}
.as-console-wrapper
{
max-height: 3em !important;
}
<span class="custom">
<div>
Width: <input id="columns" type="number" min="3" max="100" oninput="custom()">
Height: <input id="rows" type="number" min="3" max="100" oninput="custom()">
<button onclick="random()">random</button>
</div>
<div>Middle Click = set start position</div>
<div>Right Click = set end position</div>
<div id="custom"></div>
</span>

Javascript how to properly filter html divs

So I’ve been creating an html music player, and I’ve run into a problem. The problem is that when I click on an album, it filters out all the song that belong to any album, instead of filtering out the songs that only belong to the clicked album. Here is my .js files.
main.js
var btnv = 0;
var update = 0;
var NumberOfSongs = 37;
function Dropdown() {
var i = 0;
if (i == 0) {
i++;
document.getElementById("Dropbutton").classList.toggle("dropbtnclick");
document.getElementById("Dropbutton").classList.toggle("dropbtnpos");
document.getElementById("myDropdown").classList.toggle("show");
document.getElementById("PlaylistDropdown").classList.toggle("show");
document.getElementById("SearchBox").setAttribute("style", "height: 30px;");
} else {
i--;
document.getElementById("Dropbutton").classList.remove("dropbtnclick");
}}
window.onerror = function(error) {console.log(error);};
function startUI() {
var SB;
for (SB = 0; SB < NumberOfSongs;) {
SB++;
let NewSongBtn = document.createElement("a");
NewSongBtn.id = SB;
NewSongBtn.setAttribute("style", "color: white; padding: 10px 50px; text-decoration: none; text-align: left; display: block; border-top: 0.9px solid #9B9898;");
NewSongBtn.innerHTML = titles[SB] + " -- " + artists[SB];
NewSongBtn.onclick = function() {Playbutton(NewSongBtn.id);};
let LI = document.createElement("li");
LI.appendChild(NewSongBtn);
document.getElementById("SongBtns").appendChild(LI);
}
var n;
for (n = 0; n < NumberOfSongs; n++) {}
createAlbums();
}
function createAlbums() {
var AB;
for (AB = 0; AB < NumberOfSongs;) {
AB++;
if (AlbumName[AB] == "") {} else {
if (AlbumIMG[AB] == "") {} else {
let NewAlbumBtn = document.createElement("div");
NewAlbumBtn.classList.toggle("column");
NewAlbumBtn.id = AB;
NewAlbumBtn.setAttribute("style", "float: left; width: 25%; padding: 0 8px; text-align:center;align-items:center; display: inline-block; float: none; white-space: nowrap; overflow: hidden; text-overflow:ellipsis;");
//NewAlbumBtn.innerHTML = AlbumName[AB];
NewAlbumBtn.onclick = function() {PlayAlbum(NewAlbumBtn.id);};
let IMG = document.createElement("img");
IMG.src = AlbumIMG[AB];
IMG.style.width = "100%";
NewAlbumBtn.appendChild(IMG);
let text = document.createElement("p");
text.innerHTML = AlbumName[AB];
NewAlbumBtn.appendChild(text);
document.getElementById("albums").appendChild(NewAlbumBtn);
}}}}
function PlayAlbum(clicked_id) {
Id = clicked_id;
var AN;
for (AN = 0; AN < NumberOfSongs;) {
AN++;
let AB = document.getElementById(AN);
if (AlbumName[AB.id] == AlbumName[Id]) {
console.log("AlbumName " + AlbumName[Id]);
} else {
console.log("id: " + Id.id + " AB " + AB.id);
AB.remove();
}
}
}
function Update() {
let UpdateContainer = document.createElement("div");
UpdateContainer.id = "UC";
UpdateContainer.classList.toggle("NewUpdate");
document.body.appendChild(UpdateContainer);
let Updatetxt = document.createElement("div");
Updatetxt.id = "UTXT";
var wm = "Welcome to LanyxSoft Music!";
var wmr= wm.bold();
Updatetxt.innerHTML = wmr + " please note that this web player is still in beta testing mode meaning that there will most likely be issues. Thank you for you coaperation.";
Updatetxt.setAttribute("style", "z-index: 7; position: fixed; left: 50%; top: 15%; transform: translate(-50%, -50%); text-align: center; color: black; font-size: 20px; width: 430px;")
UpdateContainer.appendChild(Updatetxt);
let Updatebackground = document.createElement("div");
Updatebackground.id = "UB";
Updatebackground.classList.toggle("UpdateBackground");
document.body.appendChild(Updatebackground);
let UpdateScrollController = document.createElement("div");
UpdateScrollController.setAttribute("style", "z-index: 7; position: fixed; left: 50%; top: 40%; transform: translate(-50%, -50%); text-align: left; color: black; font-size: 20px; width: 430px; height: 120px;")
UpdateScrollController.id = "USC";
UpdateContainer.appendChild(UpdateScrollController);
let UpdateHead = document.createElement("div");
UpdateHead.id = "UH";
var u = "UPDATES";
var ur = u.bold();
UpdateHead.innerHTML = ur;
UpdateHead.setAttribute("style", "position: relative; text-align: center; color: black; font-size: 23px; width: 430px;")
UpdateScrollController.appendChild(UpdateHead);
let Updatetxt2 = document.createElement("div");
Updatetxt2.id = "UTXT2";
var UTXT2B = "Automatic button creation";
Updatetxt2.innerHTML = UTXT2B.bold() + " makes the player's ability to load faster.";
Updatetxt2.setAttribute("style", "position: relative; text-align: left; color: black; font-size: 20px; width: 430px;")
UpdateScrollController.appendChild(Updatetxt2);
let Updatetxt3 = document.createElement("div");
Updatetxt3.id = "UTXT3";
var UTXT3B = "Automatic Update notifications";
Updatetxt3.innerHTML = UTXT3B.bold() + " makes sure that when there's a new update, you will be notified.";
Updatetxt3.setAttribute("style", "position: relative; text-align: left; color: black; font-size: 20px; width: 430px;")
UpdateScrollController.appendChild(Updatetxt3);
let Updatetxt4 = document.createElement("div");
Updatetxt4.id = "UTXT4";
var UTXT4B = "More Album Art";
Updatetxt4.innerHTML = UTXT4B.bold() + " new and updated album art.";
Updatetxt4.setAttribute("style", "position: relative; text-align: left; color: black; font-size: 20px; width: 430px;")
UpdateScrollController.appendChild(Updatetxt4);
let Updatebutton = document.createElement("div");
Updatebutton.id = "UBTN";
Updatebutton.classList.toggle("UpdateCB");
Updatebutton.style.fontSize = "xx-large";
Updatebutton.innerHTML = "Continue";
Updatebutton.onclick = function() {document.getElementById("UTXT").style.visibility = "hidden"; document.getElementById("UTXT2").style.visibility = "hidden"; document.getElementById("UC").style.visibility = "hidden"; document.getElementById("UB").style.visibility = "hidden"; document.getElementById("UBTN").style.visibility = "hidden"; startUI();}
UpdateContainer.appendChild(Updatebutton);
}
var config = {apiKey:"", authDomain: "”, databaseURL: "", projectId: "", storageBucket: "", messagingSenderId: ""};
firebase.initializeApp(config);
function InitializeStartzup() {
let id = localStorage.getItem("LUDIN");
var ref = firebase.database().ref('LanyxSoft-Music-Update/' + id + '/updatestats');
ref.on('value', function(snapshot) {
startUI();
});
}
function BeginUpdate() {
var postData = {};
let id = (0|Math.random()*9e6).toString(36)+"-"+(0|Math.random()*9e6).toString(36)+"-"+(0|Math.random()*9e6).toString(36);
var updates = {};
let L = localStorage.getItem("LUDIN");
Update();
firebase.database().ref('LanyxSoft-Music-Update/' + L).set({
updated : "true"
});
var ref = firebase.database().ref().child('/LanyxSoft-Music-Update/'+id);
ref.on("child_added", function(child) {
var IDofFriends = child.val();
if(IDofFriends == localStorage.getItem("LUDIN")) {
console.log("func: child_added result: User id matches to id in accepted LanyxSoft database");
} else {
console.log("func: child_added result: User id doesn't match to id in accepted LanyxSoft database");
}
});
//updates["/posts/" + "hihihihihi"] = postData;
return firebase.database().ref().update(updates);
}
//child_added
function SetID() {
let id = (0|Math.random()*9e6).toString(36)+"-"+(0|Math.random()*9e6).toString(36)+"-"+(0|Math.random()*9e6).toString(36);
localStorage.setItem("LUDIN", id);
BeginUpdate();
}
// Check browser support
if (typeof(Storage) !== "undefined") {
if (localStorage.getItem("LUDIN") == null) {
console.log("func: SetID() result:", true);
SetID();
} else {
console.log("func: InitializeStartzup() result:", true); //console.log("func: InitializeStartzup() result: func success= "+ true);
InitializeStartzup();
}
} else {
Update();
console.log("s means that some feature aren't available on this device");
}
function drop() {
}
window.onclick = function(event, clicked_id) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
//openDropdown.classList.remove('show');
}}}}
//labels
//buttons
var input = document.getElementById("button");
var input2 = document.getElementById("button2");
//text/labels/numbers
//number vals
var num = 1;
var a = new Date();
var mt = a.getMonth() + 1;
var dy = a.getDate();
var yr = a.getFullYear();
var tm = a.getHours()+":"+a.getMinutes();
var dateFormat = mt+"/"+dy+"/"+yr+"_"+tm;
//labels
var audiotitle = document.getElementById("audiotitle");
var audioartist = document.getElementById("artist");
var image = document.getElementById("AlbumArt");
var x = document.getElementById("myAudio");
var percent = document.getElementById("currentlbl");
audiotitle.innerHTML = x.title;
//inputslider
var slider = document.getElementById("myRange");
slider.oninput = function() {
percent.innerHTML = this.value + "%";
x.currentTime = slider.value;
}
//device orientation functions
function zoomOutMobile() {
var viewport = document.querySelector('meta[name="viewport"]');
if ( viewport ) {
viewport.content = "width=device-width, initial-scale=1.0";
}
}
function readDeviceOrientation() {
switch (window.orientation) {
case 0:
// Portrait
document.getElementById("PlaylistC").style.visibility = "hidden";
document.getElementById("PlaylistC").style.display = "none";
document.getElementById("container").setAttribute("style", "top: 5%; position: relative; width: 330px; min-height:480px; background: #333; overflow: auto; margin: 20px auto; border-radius: 10px; box-shadow: 0 10px 8px -8px #333; align-items: center; text-align: center;");
break;
case 180:
// Portrait (Upside-down)
document.getElementById("PlaylistC").style.visibility = "hidden";
document.getElementById("PlaylistC").style.display = "none";
document.getElementById("container").setAttribute("style", "top: 5%; position: relative; width: 330px; min-height:480px; background: #333; overflow: auto; margin: 20px auto; border-radius: 10px; box-shadow: 0 10px 8px -8px #333; align-items: center; text-align: center;");
break;
case -90:
// Landscape (Clockwise)
document.getElementById("PlaylistC").style.visibility = "visible";
document.getElementById("PlaylistC").style.display = "block";
document.getElementById("container").setAttribute("style", "position: relative; width: 330px; min-height:480px; background: #333; overflow: auto; margin: 0px; left: 0; border-radius: 10px; box-shadow: 0 10px 8px -8px #333; align-items: center; text-align: center;");
zoomOutMobile();
break;
case 90:
// Landscape (Counterclockwise)
document.getElementById("PlaylistC").style.visibility = "visible";
document.getElementById("PlaylistC").style.display = "block";
document.getElementById("container").setAttribute("style", "position: relative; width: 330px; min-height:480px; background: #333; overflow: auto; margin: 0px; left: 0; border-radius: 10px; box-shadow: 0 10px 8px -8px #333; align-items: center; text-align: center;");
zoomOutMobile();
break;
}
}
readDeviceOrientation();
window.onorientationchange = readDeviceOrientation;
//SEARCH
//document.getElementById("SearchBox").addEventListener("keyup",);
function search() {
var input, filter, ui, li, a, w;
input = document.getElementById("SearchBox");
filter = input.value.toUpperCase();
ui = document.getElementById("PlaylistDropdown");
li = ui.getElementsByTagName("li");
//function for dd
for (w = 0; w < li.length; w++) {
a = li[w].getElementsByTagName("a")[0];
if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
li[w].style.display = "";
} else {
li[w].style.display = "none";
}}
}
/*function searchAlbums() {
var input, filter, ui, li, a, w;
input = document.getElementById("SearchBox");
filter = input.value.toUpperCase();
ui = document.getElementById("albums");
li = ui.getElementsByTagName("div");
//function for dd
for (w = 0; w < li.length; w++) {
a = li[w].getElementsByTagName("p")[0];
if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
li[w].style.display = "";
} else {
li[w].style.display = "none";
}}
}*/
function Shuffle() {
var s = Math.floor(Math.random() * NumberOfSongs) + 1;
x.title = titles[s];
audiotitle.innerHTML = x.title;
audioartist.innerHTML = artists[s];
if (albumart[s] == "") {
image.src = "https://iplock.weebly.com/uploads/9/5/7/3/95731436/p164.png";
} else {
image.src = albumart[s];
}
x.src = songs[s];
x.play();
num = 1;
playAudio();
}
var i = 1;
function keys() {
if (x.currentTime == x.duration) {
//x.src = sources.two;
i++;
x.title = titles[i];
audiotitle.innerHTML = x.title;
audioartist.innerHTML = artists[i];
if (albumart[i] == "") {
image.src = "https://iplock.weebly.com/uploads/9/5/7/3/95731436/p164.png";
} else {
image.src = albumart[i];
}
x.src = songs[i];
x.play();
num = 1;
playAudio();
}}
function next() {
i++;
x.title = titles[i];
audiotitle.innerHTML = x.title;
audioartist.innerHTML = artists[i];
if (albumart[i] == "") {
image.src = "https://iplock.weebly.com/uploads/9/5/7/3/95731436/p164.png";
} else {
image.src = albumart[i];
}
x.src = songs[i];
x.play();
num = 1;
playAudio();
}
function rewind() {
i--;
x.title = titles[i];
audiotitle.innerHTML = x.title;
audioartist.innerHTML = artists[i];
if (albumart[i] == "") {
image.src = "https://iplock.weebly.com/uploads/9/5/7/3/95731436/p164.png";
} else {
image.src = albumart[i];
}
x.src = songs[i];
x.play();
num = 1;
playAudio();
}
function Playbutton(clicked_id) {
i = clicked_id;
x.title = titles[i];
audiotitle.innerHTML = x.title;
audioartist.innerHTML = artists[i];
if (albumart[i] == "") {
image.src = "https://iplock.weebly.com/uploads/9/5/7/3/95731436/p164.png";
} else {
image.src = albumart[i];
}
x.src = songs[i];
x.play();
num = 1;
playAudio();
}
function startup() {
input2.style.display="none";
}
startup()
function playAudio() {
x.play();
if (num == 1) {
x.play();
//text.innerHTML = "pause";
input.style.display="none";
input2.style="visibility:visible;";
input2.style.display="block";
num = 0;
d = dateFormat + "playing";
} else {
x.pause();
//text.innerHTML = "play";
input2.style="visibility:hidden;";
input2.style.display="none";
input.style="visibility:visable;";
num = 1;
d = dateFormat + "paused";
}}
window.addEventListener('load', function() {
var cur = document.querySelector('#perc'),
vid = document.querySelector('#myAudio')
dur = document.getElementById("durationlbl");
per = document.getElementById("currentlbl");
})
myAudio.addEventListener('timeupdate', function(e) {
//current time
per.textContent = sToTime(e.target.currentTime);
//duraion
dur.textContent = sToTime(e.target.duration);
slider.value = x.currentTime;
//percent.innerHTML = x.currentTime;
slider.max = x.duration;
keys();
})
function sToTime(t) {
return padZero(parseInt((t / (60 * 60)) % 24)) + ":" +
padZero(parseInt((t / (60)) % 60)) + ":" +
padZero(parseInt((t) % 60));
}
function padZero(v) {
return (v < 10) ? "0" + v : v;
}
So in main.js I have the “brains” i guess, of the entire player. The function PlayAlbum(clicked_id) is the problem. That’s the function that is supposed to filter all the songs so that the only songs left are the ones from the clicked album.
song-list.js
So in song-list.js i just have the list of songs and the album art for it. I also have the link to the file. For you guys’s Sake i really should organize this better, but that’ll happen in a little bit. I didn’t include the code in here because its not an important factor to my problem.
variables.js
var AlbumName = {
1 : "",
2 : "",
3 : "",
4 : "",
5 : "Mania",
6 : "",
7 : "",
8 : "",
9 : "American Beauty/American Psycho",
10 : "",
11 : "Vessel",
12 : "",
13 : "Vessel",
14 : "American Beauty/American Psycho",
15 : "",
16 : "",
17 : "",
18 : "",
19 : "",
20 : "",
21 : "",
22 : "",
23 : "Vessel",
24 : "",
25 : "",
26 : "",
27 : "",
28 : "",
29 : "",
30 : "",
31 : "",
32 : "",
33 : "Mania",
34 : "Watching the Sky",
35 : "",
36 : "",
37 : ""
}
var AlbumIMG = {
1 : "",
2 : "",
3 : "https://vignette.wikia.nocookie.net/monstercat/images/0/0c/Marshmello_-_Alone.jpg/revision/latest?cb=20160513204533",
4 : "",
5 : "https://images-na.ssl-images-amazon.com/images/I/41K3SuHNQpL._SS500.jpg",
6 : "",
7 : "",
8 : "",
9 : "https://upload.wikimedia.org/wikipedia/en/b/b6/American_Beauty_American_Psycho_cover.png",
10 : "",
11 : "https://images-na.ssl-images-amazon.com/images/I/41%2BCuqqyyvL.jpg",
12 : "",
13 : "https://images-na.ssl-images-amazon.com/images/I/41%2BCuqqyyvL.jpg",
14 : "https://upload.wikimedia.org/wikipedia/en/b/b6/American_Beauty_American_Psycho_cover.png",
15 : "",
16 : "",
17 : "",
18 : "",
19 : "",
20 : "",
21 : "",
22 : "",
23 : "https://images-na.ssl-images-amazon.com/images/I/41%2BCuqqyyvL.jpg",
24 : "",
25 : "",
26 : "",
27 : "",
28 : "",
29 : "",
30 : "",
31 : "",
32 : "",
33 : "https://images-na.ssl-images-amazon.com/images/I/41K3SuHNQpL._SS500.jpg",
34 : "https://iplock.weebly.com/uploads/9/5/7/3/95731436/p184.png",
35 : "",
36 : "",
37 : ""
}
So the variables.js file is just the list of the albums, like the first set of variables is the list of songs and what album they belong to. The second is the links to the album art for the specified album.
To see my full code go to https://github.com/lightning417techa/Music
EDIT 2
I was thinking about simplifying this a bit but i came to a point where if i did simplify the creation of the song buttons and the album buttons, it throws an error. I also noticed that i cant set the ids as a number.
I'm pretty sure let AB = document.getElementById(AN); is your issue. Throw a debugger in after that line and make sure it's populating the way you expect it to. I'm fairly certain that ids can't be numbers and you're expecting them to be (if I'm reading this all correctly).
So i went old school and actually grabbed a whiteboard and wrote my idea down. I came to realization that in the function StartUI() it sets The I’d of the button to a number, then i read the documentation on w3schools and i saw that i can remove part of a string for example if i did document.getElementById(“Text”).innerHTML = MyEditedText; would turn out to
let myText = "hello1";
document.getElementById(“Text”).innerHTML = myText;
function MyFunction() {
let MyEditedText = myText.replace("hello", "");
document.getElementById(“Text”).innerHTML = MyEditedText;
}
<p id=“Text”></p>
<button onclick=“MyFunction”>Click Me</button>

Correctly Displaying Data in optgroups

I am having an issue with MYSQL displaying results correctly when I add the php code to the snippet below.
When it runs it displays everything correctly except when I click on the <optgroup> it only reads the first <option></option> rather than reading everything in the <optgroup></optgroup> When I try to use GROUP BY in the MYSQL everything is fixed except it only displays a single column from my database rather than everything filtered.
I am pretty sure the error is somewhere in my PHP code as I think the code is writing an optgroup for every option so it is reading it something like this
<optgroup>
<option>option 1</option>
</optgroup>
<optgroup>
<option>option 2</option>
</optgroup>
<optgroup>
<option>option 3</option>
</optgroup>
MY PHP code:
<?php $sql = "SELECT * FROM `users`,`departments` WHERE users.dept = departments.dept_name";
$query = mysql_query($sql);
echo "<select name='test[]' id='optgroup' class='ms' multiple='multiple'>";?>
<?php while ($row = mysql_fetch_array($query)) {
echo "<optgroup label=".$row['dept_name'].">
<option value=".$row['user_name'].">".$row['user_name']."</option>
</optgroup>";}?>
</select>
USERS TABLE ARCHETICTURE:
CREATE TABLE users (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`user_role` varchar(255) NOT NULL,
`user_name` varchar(255) NOT NULL,
`gender` varchar(255) NOT NULL,
`dob` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`address` varchar(255) NOT NULL,
`phone` varchar(30) NOT NULL,
`dept` varchar(255) NOT NULL,
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`userpic` varchar(255) NOT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1
DEPARTMENTS TABLE ARCHETICTURE:
departments
CREATE TABLE `departments` (
`dept_id` int(11) NOT NULL AUTO_INCREMENT,
`dept_name` varchar(255) NOT NULL,
`dept_supervisor` varchar(255) NOT NULL,
`dept_desc` varchar(255) NOT NULL,
`dept_email` varchar(255) NOT NULL,
`dept_phone` varchar(100) NOT NULL,
PRIMARY KEY (`dept_id`)
) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=latin1
SNIPPET:
/*
* MultiSelect v0.9.12
* Copyright (c) 2012 Louis Cuny
*
* This program is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What The Fuck You Want
* To Public License, Version 2, as published by Sam Hocevar. See
* http://sam.zoy.org/wtfpl/COPYING for more details.
*/
!function ($) {
"use strict";
/* MULTISELECT CLASS DEFINITION
* ====================== */
var MultiSelect = function (element, options) {
this.options = options;
this.$element = $(element);
this.$container = $('<div/>', { 'class': "ms-container" });
this.$selectableContainer = $('<div/>', { 'class': 'ms-selectable' });
this.$selectionContainer = $('<div/>', { 'class': 'ms-selection' });
this.$selectableUl = $('<ul/>', { 'class': "ms-list", 'tabindex' : '-1' });
this.$selectionUl = $('<ul/>', { 'class': "ms-list", 'tabindex' : '-1' });
this.scrollTo = 0;
this.elemsSelector = 'li:visible:not(.ms-optgroup-label,.ms-optgroup-container,.'+options.disabledClass+')';
};
MultiSelect.prototype = {
constructor: MultiSelect,
init: function(){
var that = this,
ms = this.$element;
if (ms.next('.ms-container').length === 0){
ms.css({ position: 'absolute', left: '-9999px' });
ms.attr('id', ms.attr('id') ? ms.attr('id') : Math.ceil(Math.random()*1000)+'multiselect');
this.$container.attr('id', 'ms-'+ms.attr('id'));
this.$container.addClass(that.options.cssClass);
ms.find('option').each(function(){
that.generateLisFromOption(this);
});
this.$selectionUl.find('.ms-optgroup-label').hide();
if (that.options.selectableHeader){
that.$selectableContainer.append(that.options.selectableHeader);
}
that.$selectableContainer.append(that.$selectableUl);
if (that.options.selectableFooter){
that.$selectableContainer.append(that.options.selectableFooter);
}
if (that.options.selectionHeader){
that.$selectionContainer.append(that.options.selectionHeader);
}
that.$selectionContainer.append(that.$selectionUl);
if (that.options.selectionFooter){
that.$selectionContainer.append(that.options.selectionFooter);
}
that.$container.append(that.$selectableContainer);
that.$container.append(that.$selectionContainer);
ms.after(that.$container);
that.activeMouse(that.$selectableUl);
that.activeKeyboard(that.$selectableUl);
var action = that.options.dblClick ? 'dblclick' : 'click';
that.$selectableUl.on(action, '.ms-elem-selectable', function(){
that.select($(this).data('ms-value'));
});
that.$selectionUl.on(action, '.ms-elem-selection', function(){
that.deselect($(this).data('ms-value'));
});
that.activeMouse(that.$selectionUl);
that.activeKeyboard(that.$selectionUl);
ms.on('focus', function(){
that.$selectableUl.focus();
});
}
var selectedValues = ms.find('option:selected').map(function(){ return $(this).val(); }).get();
that.select(selectedValues, 'init');
if (typeof that.options.afterInit === 'function') {
that.options.afterInit.call(this, this.$container);
}
},
'generateLisFromOption' : function(option, index, $container){
var that = this,
ms = that.$element,
attributes = "",
$option = $(option);
for (var cpt = 0; cpt < option.attributes.length; cpt++){
var attr = option.attributes[cpt];
if(attr.name !== 'value' && attr.name !== 'disabled'){
attributes += attr.name+'="'+attr.value+'" ';
}
}
var selectableLi = $('<li '+attributes+'><span>'+that.escapeHTML($option.text())+'</span></li>'),
selectedLi = selectableLi.clone(),
value = $option.val(),
elementId = that.sanitize(value);
selectableLi
.data('ms-value', value)
.addClass('ms-elem-selectable')
.attr('id', elementId+'-selectable');
selectedLi
.data('ms-value', value)
.addClass('ms-elem-selection')
.attr('id', elementId+'-selection')
.hide();
if ($option.prop('disabled') || ms.prop('disabled')){
selectedLi.addClass(that.options.disabledClass);
selectableLi.addClass(that.options.disabledClass);
}
var $optgroup = $option.parent('optgroup');
if ($optgroup.length > 0){
var optgroupLabel = $optgroup.attr('label'),
optgroupId = that.sanitize(optgroupLabel),
$selectableOptgroup = that.$selectableUl.find('#optgroup-selectable-'+optgroupId),
$selectionOptgroup = that.$selectionUl.find('#optgroup-selection-'+optgroupId);
if ($selectableOptgroup.length === 0){
var optgroupContainerTpl = '<li class="ms-optgroup-container"></li>',
optgroupTpl = '<ul class="ms-optgroup"><li class="ms-optgroup-label"><span>'+optgroupLabel+'</span></li></ul>';
$selectableOptgroup = $(optgroupContainerTpl);
$selectionOptgroup = $(optgroupContainerTpl);
$selectableOptgroup.attr('id', 'optgroup-selectable-'+optgroupId);
$selectionOptgroup.attr('id', 'optgroup-selection-'+optgroupId);
$selectableOptgroup.append($(optgroupTpl));
$selectionOptgroup.append($(optgroupTpl));
if (that.options.selectableOptgroup){
$selectableOptgroup.find('.ms-optgroup-label').on('click', function(){
var values = $optgroup.children(':not(:selected, :disabled)').map(function(){ return $(this).val();}).get();
that.select(values);
});
$selectionOptgroup.find('.ms-optgroup-label').on('click', function(){
var values = $optgroup.children(':selected:not(:disabled)').map(function(){ return $(this).val();}).get();
that.deselect(values);
});
}
that.$selectableUl.append($selectableOptgroup);
that.$selectionUl.append($selectionOptgroup);
}
index = index === undefined ? $selectableOptgroup.find('ul').children().length : index + 1;
selectableLi.insertAt(index, $selectableOptgroup.children());
selectedLi.insertAt(index, $selectionOptgroup.children());
} else {
index = index === undefined ? that.$selectableUl.children().length : index;
selectableLi.insertAt(index, that.$selectableUl);
selectedLi.insertAt(index, that.$selectionUl);
}
},
'addOption' : function(options){
var that = this;
if (options.value !== undefined && options.value !== null){
options = [options];
}
$.each(options, function(index, option){
if (option.value !== undefined && option.value !== null &&
that.$element.find("option[value='"+option.value+"']").length === 0){
var $option = $('<option value="'+option.value+'">'+option.text+'</option>'),
index = parseInt((typeof option.index === 'undefined' ? that.$element.children().length : option.index)),
$container = option.nested === undefined ? that.$element : $("optgroup[label='"+option.nested+"']");
$option.insertAt(index, $container);
that.generateLisFromOption($option.get(0), index, option.nested);
}
});
},
'escapeHTML' : function(text){
return $("<div>").text(text).html();
},
'activeKeyboard' : function($list){
var that = this;
$list.on('focus', function(){
$(this).addClass('ms-focus');
})
.on('blur', function(){
$(this).removeClass('ms-focus');
})
.on('keydown', function(e){
switch (e.which) {
case 40:
case 38:
e.preventDefault();
e.stopPropagation();
that.moveHighlight($(this), (e.which === 38) ? -1 : 1);
return;
case 37:
case 39:
e.preventDefault();
e.stopPropagation();
that.switchList($list);
return;
case 9:
if(that.$element.is('[tabindex]')){
e.preventDefault();
var tabindex = parseInt(that.$element.attr('tabindex'), 10);
tabindex = (e.shiftKey) ? tabindex-1 : tabindex+1;
$('[tabindex="'+(tabindex)+'"]').focus();
return;
}else{
if(e.shiftKey){
that.$element.trigger('focus');
}
}
}
if($.inArray(e.which, that.options.keySelect) > -1){
e.preventDefault();
e.stopPropagation();
that.selectHighlighted($list);
return;
}
});
},
'moveHighlight': function($list, direction){
var $elems = $list.find(this.elemsSelector),
$currElem = $elems.filter('.ms-hover'),
$nextElem = null,
elemHeight = $elems.first().outerHeight(),
containerHeight = $list.height(),
containerSelector = '#'+this.$container.prop('id');
$elems.removeClass('ms-hover');
if (direction === 1){ // DOWN
$nextElem = $currElem.nextAll(this.elemsSelector).first();
if ($nextElem.length === 0){
var $optgroupUl = $currElem.parent();
if ($optgroupUl.hasClass('ms-optgroup')){
var $optgroupLi = $optgroupUl.parent(),
$nextOptgroupLi = $optgroupLi.next(':visible');
if ($nextOptgroupLi.length > 0){
$nextElem = $nextOptgroupLi.find(this.elemsSelector).first();
} else {
$nextElem = $elems.first();
}
} else {
$nextElem = $elems.first();
}
}
} else if (direction === -1){ // UP
$nextElem = $currElem.prevAll(this.elemsSelector).first();
if ($nextElem.length === 0){
var $optgroupUl = $currElem.parent();
if ($optgroupUl.hasClass('ms-optgroup')){
var $optgroupLi = $optgroupUl.parent(),
$prevOptgroupLi = $optgroupLi.prev(':visible');
if ($prevOptgroupLi.length > 0){
$nextElem = $prevOptgroupLi.find(this.elemsSelector).last();
} else {
$nextElem = $elems.last();
}
} else {
$nextElem = $elems.last();
}
}
}
if ($nextElem.length > 0){
$nextElem.addClass('ms-hover');
var scrollTo = $list.scrollTop() + $nextElem.position().top -
containerHeight / 2 + elemHeight / 2;
$list.scrollTop(scrollTo);
}
},
'selectHighlighted' : function($list){
var $elems = $list.find(this.elemsSelector),
$highlightedElem = $elems.filter('.ms-hover').first();
if ($highlightedElem.length > 0){
if ($list.parent().hasClass('ms-selectable')){
this.select($highlightedElem.data('ms-value'));
} else {
this.deselect($highlightedElem.data('ms-value'));
}
$elems.removeClass('ms-hover');
}
},
'switchList' : function($list){
$list.blur();
this.$container.find(this.elemsSelector).removeClass('ms-hover');
if ($list.parent().hasClass('ms-selectable')){
this.$selectionUl.focus();
} else {
this.$selectableUl.focus();
}
},
'activeMouse' : function($list){
var that = this;
this.$container.on('mouseenter', that.elemsSelector, function(){
$(this).parents('.ms-container').find(that.elemsSelector).removeClass('ms-hover');
$(this).addClass('ms-hover');
});
this.$container.on('mouseleave', that.elemsSelector, function () {
$(this).parents('.ms-container').find(that.elemsSelector).removeClass('ms-hover');
});
},
'refresh' : function() {
this.destroy();
this.$element.multiSelect(this.options);
},
'destroy' : function(){
$("#ms-"+this.$element.attr("id")).remove();
this.$element.off('focus');
this.$element.css('position', '').css('left', '');
this.$element.removeData('multiselect');
},
'select' : function(value, method){
if (typeof value === 'string'){ value = [value]; }
var that = this,
ms = this.$element,
msIds = $.map(value, function(val){ return(that.sanitize(val)); }),
selectables = this.$selectableUl.find('#' + msIds.join('-selectable, #')+'-selectable').filter(':not(.'+that.options.disabledClass+')'),
selections = this.$selectionUl.find('#' + msIds.join('-selection, #') + '-selection').filter(':not(.'+that.options.disabledClass+')'),
options = ms.find('option:not(:disabled)').filter(function(){ return($.inArray(this.value, value) > -1); });
if (method === 'init'){
selectables = this.$selectableUl.find('#' + msIds.join('-selectable, #')+'-selectable'),
selections = this.$selectionUl.find('#' + msIds.join('-selection, #') + '-selection');
}
if (selectables.length > 0){
selectables.addClass('ms-selected').hide();
selections.addClass('ms-selected').show();
options.prop('selected', true);
that.$container.find(that.elemsSelector).removeClass('ms-hover');
var selectableOptgroups = that.$selectableUl.children('.ms-optgroup-container');
if (selectableOptgroups.length > 0){
selectableOptgroups.each(function(){
var selectablesLi = $(this).find('.ms-elem-selectable');
if (selectablesLi.length === selectablesLi.filter('.ms-selected').length){
$(this).find('.ms-optgroup-label').hide();
}
});
var selectionOptgroups = that.$selectionUl.children('.ms-optgroup-container');
selectionOptgroups.each(function(){
var selectionsLi = $(this).find('.ms-elem-selection');
if (selectionsLi.filter('.ms-selected').length > 0){
$(this).find('.ms-optgroup-label').show();
}
});
} else {
if (that.options.keepOrder && method !== 'init'){
var selectionLiLast = that.$selectionUl.find('.ms-selected');
if((selectionLiLast.length > 1) && (selectionLiLast.last().get(0) != selections.get(0))) {
selections.insertAfter(selectionLiLast.last());
}
}
}
if (method !== 'init'){
ms.trigger('change');
if (typeof that.options.afterSelect === 'function') {
that.options.afterSelect.call(this, value);
}
}
}
},
'deselect' : function(value){
if (typeof value === 'string'){ value = [value]; }
var that = this,
ms = this.$element,
msIds = $.map(value, function(val){ return(that.sanitize(val)); }),
selectables = this.$selectableUl.find('#' + msIds.join('-selectable, #')+'-selectable'),
selections = this.$selectionUl.find('#' + msIds.join('-selection, #')+'-selection').filter('.ms-selected').filter(':not(.'+that.options.disabledClass+')'),
options = ms.find('option').filter(function(){ return($.inArray(this.value, value) > -1); });
if (selections.length > 0){
selectables.removeClass('ms-selected').show();
selections.removeClass('ms-selected').hide();
options.prop('selected', false);
that.$container.find(that.elemsSelector).removeClass('ms-hover');
var selectableOptgroups = that.$selectableUl.children('.ms-optgroup-container');
if (selectableOptgroups.length > 0){
selectableOptgroups.each(function(){
var selectablesLi = $(this).find('.ms-elem-selectable');
if (selectablesLi.filter(':not(.ms-selected)').length > 0){
$(this).find('.ms-optgroup-label').show();
}
});
var selectionOptgroups = that.$selectionUl.children('.ms-optgroup-container');
selectionOptgroups.each(function(){
var selectionsLi = $(this).find('.ms-elem-selection');
if (selectionsLi.filter('.ms-selected').length === 0){
$(this).find('.ms-optgroup-label').hide();
}
});
}
ms.trigger('change');
if (typeof that.options.afterDeselect === 'function') {
that.options.afterDeselect.call(this, value);
}
}
},
'select_all' : function(){
var ms = this.$element,
values = ms.val();
ms.find('option:not(":disabled")').prop('selected', true);
this.$selectableUl.find('.ms-elem-selectable').filter(':not(.'+this.options.disabledClass+')').addClass('ms-selected').hide();
this.$selectionUl.find('.ms-optgroup-label').show();
this.$selectableUl.find('.ms-optgroup-label').hide();
this.$selectionUl.find('.ms-elem-selection').filter(':not(.'+this.options.disabledClass+')').addClass('ms-selected').show();
this.$selectionUl.focus();
ms.trigger('change');
if (typeof this.options.afterSelect === 'function') {
var selectedValues = $.grep(ms.val(), function(item){
return $.inArray(item, values) < 0;
});
this.options.afterSelect.call(this, selectedValues);
}
},
'deselect_all' : function(){
var ms = this.$element,
values = ms.val();
ms.find('option').prop('selected', false);
this.$selectableUl.find('.ms-elem-selectable').removeClass('ms-selected').show();
this.$selectionUl.find('.ms-optgroup-label').hide();
this.$selectableUl.find('.ms-optgroup-label').show();
this.$selectionUl.find('.ms-elem-selection').removeClass('ms-selected').hide();
this.$selectableUl.focus();
ms.trigger('change');
if (typeof this.options.afterDeselect === 'function') {
this.options.afterDeselect.call(this, values);
}
},
sanitize: function(value){
var hash = 0, i, character;
if (value.length == 0) return hash;
var ls = 0;
for (i = 0, ls = value.length; i < ls; i++) {
character = value.charCodeAt(i);
hash = ((hash<<5)-hash)+character;
hash |= 0; // Convert to 32bit integer
}
return hash;
}
};
/* MULTISELECT PLUGIN DEFINITION
* ======================= */
$.fn.multiSelect = function () {
var option = arguments[0],
args = arguments;
return this.each(function () {
var $this = $(this),
data = $this.data('multiselect'),
options = $.extend({}, $.fn.multiSelect.defaults, $this.data(), typeof option === 'object' && option);
if (!data){ $this.data('multiselect', (data = new MultiSelect(this, options))); }
if (typeof option === 'string'){
data[option](args[1]);
} else {
data.init();
}
});
};
$.fn.multiSelect.defaults = {
keySelect: [32],
selectableOptgroup: false,
disabledClass : 'disabled',
dblClick : false,
keepOrder: false,
cssClass: ''
};
$.fn.multiSelect.Constructor = MultiSelect;
$.fn.insertAt = function(index, $parent) {
return this.each(function() {
if (index === 0) {
$parent.prepend(this);
} else {
$parent.children().eq(index - 1).after(this);
}
});
};
}(window.jQuery);
//Multi-select
$('#optgroup').multiSelect({ selectableOptgroup: true });
.ms-container{
background: transparent url('../img/switch.png') no-repeat 50% 50%;
width: 370px;
}
.ms-container:after{
content: ".";
display: block;
height: 0;
line-height: 0;
font-size: 0;
clear: both;
min-height: 0;
visibility: hidden;
}
.ms-container .ms-selectable, .ms-container .ms-selection{
background: #fff;
color: #555555;
float: left;
width: 45%;
}
.ms-container .ms-selection{
float: right;
}
.ms-container .ms-list{
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
-moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
-webkit-transition: border linear 0.2s, box-shadow linear 0.2s;
-moz-transition: border linear 0.2s, box-shadow linear 0.2s;
-ms-transition: border linear 0.2s, box-shadow linear 0.2s;
-o-transition: border linear 0.2s, box-shadow linear 0.2s;
transition: border linear 0.2s, box-shadow linear 0.2s;
border: 1px solid #ccc;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
position: relative;
height: 200px;
padding: 0;
overflow-y: auto;
}
.ms-container .ms-list.ms-focus{
border-color: rgba(82, 168, 236, 0.8);
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6);
-moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6);
outline: 0;
outline: thin dotted \9;
}
.ms-container ul{
margin: 0;
list-style-type: none;
padding: 0;
}
.ms-container .ms-optgroup-container{
width: 100%;
}
.ms-container .ms-optgroup-label{
margin: 0;
padding: 5px 0px 0px 5px;
cursor: pointer;
color: #999;
}
.ms-container .ms-selectable li.ms-elem-selectable,
.ms-container .ms-selection li.ms-elem-selection{
border-bottom: 1px #eee solid;
padding: 2px 10px;
color: #555;
font-size: 14px;
}
.ms-container .ms-selectable li.ms-hover,
.ms-container .ms-selection li.ms-hover{
cursor: pointer;
color: #fff;
text-decoration: none;
background-color: #08c;
}
.ms-container .ms-selectable li.disabled,
.ms-container .ms-selection li.disabled{
background-color: #eee;
color: #aaa;
cursor: text;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="optgroup" class="ms" multiple="multiple">
<optgroup label="Department 1">
<option value="employee_1">Employee 1</option>
<option value="employee_2">Employee 2</option>
<option value="employee_3">Employee 3</option>
</optgroup>
<optgroup label="Department 2">
<option value="employee_4">Employee 4</option>
<option value="employee_5">Employee 5</option>
<option value="employee_6">Employee 6</option>
</optgroup>
</select>
Here is the alternative method, which only takes 1 query. Take a look at how I ordered the query it's basicaly the same idea as with the other answear except you're not making N query * the number of departments
<?php
echo '<select name="test[]" id="optgroup" class="ms" multiple="multiple">', "\n";
$select = mysql_query( '
SELECT
*
FROM `users`, `departments`
WHERE `users`.`dept` = `departments`.`dept_name`
ORDER BY `departments`.`dept_name`, `users`.`user_name` ASC
' );
$department = false;
if( mysql_num_rows( $select ) ){
while( $row = mysql_fetch_array( $select ) ){
if( ! $department || ( $department && $department != $row['dept_name'] ) ){
// use some sort of character escapeing to prevent XSS
if( $department ){
echo '</optgroup>', "\n";
}
echo '<optgroup label="', htmlspecialchars( $row['dept_name'] ), '">', "\n";
$department = $row['dept_name'];
}
echo '<option value="', htmlspecialchars( $row['user_name'] ), '">',
htmlspecialchars( $row['user_name'] ),
'</option>', "\n";
}
echo '</optgroup>', "\n";
}
echo '</select>', "\n";
you should first get department names and then for each department, execute a query :
<?php
echo '<select name="test[]" id="optgroup" class="ms" multiple="multiple">';
$departments = mysql_query( 'SELECT DISTINCT dept_name FROM `departments`' );
while( $row = mysql_fetch_array( $departments ) ){
// use some sort of character escapeing to prevent XSS
echo '<optgroup label="', htmlspecialchars( $row['dept_name'] ), '">';
$users = mysql_query( sprintf( 'SELECT user_name FROM `users` WHERE users.dept = "%s"', mysql_real_escape_string( $row['dept_name'] ) ) );
while( $user = mysql_fetch_array( $users ) ){
echo '<option value="', htmlspecialchars( $user['user_name'] ), '">',
htmlspecialchars( $user['user_name'] ),
'</option>';
}
echo '</optgroup>';
}
echo '</select>';

How to highlight search text in html with the help of js?

I am passing a very very hard time with JavaScript and I have zero knowledge with jQuery. I am trying to highlight a text from a page or from a body with the help of JavaScript and jQuery.
With hard try, I manage a search code with highlight.
My HTML code:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="/javascripts/application.js" type="text/javascript">
</head>
<body>
Search: <input type="text" id="text-search" />
<p>
<b>Demo </b> he new edition of KnowlEdge K12 enables your school with flexibility by wholly automating their administrative and academic processes. With IncTech’s solution for K12 schools, you can. We give you an internal infrastructure so you can share school and student information.
</p>
</body>
My full code with jQuery and JavaScript:
jQuery.fn.highlight = function(pat) {
function innerHighlight(node, pat) {
var skip = 0;
if (node.nodeType == 3) {
var pos = node.data.toUpperCase().indexOf(pat);
if (pos >= 0) {
var spannode = document.createElement('span');
spannode.className = 'highlight';
var middlebit = node.splitText(pos);
var endbit = middlebit.splitText(pat.length);
var middleclone = middlebit.cloneNode(true);
spannode.appendChild(middleclone);
middlebit.parentNode.replaceChild(spannode, middlebit);
skip = 1;
}
} else if (node.nodeType == 1 && node.childNodes && !/(script|style) /i.test(node.tagName)) {
for (var i = 0; i < node.childNodes.length; ++i) {
i += innerHighlight(node.childNodes[i], pat);
}
}
return skip;
}
return this.each(function() {
innerHighlight(this, pat.toUpperCase());
});
};
jQuery.fn.removeHighlight = function() {
function newNormalize(node) {
for (var i = 0, children = node.childNodes, nodeCount = children.length; i < nodeCount; i++) {
var child = children[i];
if (child.nodeType == 1) {
newNormalize(child);
continue;
}
if (child.nodeType != 3) { continue; }
var next = child.nextSibling;
if (next == null || next.nodeType != 3) { continue; }
var combined_text = child.nodeValue + next.nodeValue;
new_node = node.ownerDocument.createTextNode(combined_text);
node.insertBefore(new_node, child);
node.removeChild(child);
node.removeChild(next);
i--;
nodeCount--;
}
}
return this.find("span.highlight").each(function() {
var thisParent = this.parentNode;
thisParent.replaceChild(this.firstChild, this);
newNormalize(thisParent);
}).end();
};
$(function() {
$('#text-search').bind('keyup change', function(ev) {
// pull in the new value
var searchTerm = $(this).val();
// remove any old highlighted terms
$('body').removeHighlight();
// disable highlighting if empty
if ( searchTerm ) {
// highlight the new term
$('body').highlight( searchTerm );
}
});
});
.highlight {
background-color: #fff34d;
-moz-border-radius: 5px; /* FF1+ */
-webkit-border-radius: 5px; /* Saf3-4 */
border-radius: 5px; /* Opera 10.5, IE 9, Saf5, Chrome */
-moz-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.7); /* FF3.5+ */
-webkit-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.7); /* Saf3.0+, Chrome */
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.7); /* Opera 10.5+, IE 9.0 */
}
.highlight {
padding:1px 4px;
margin:0 -4px;
}
Please don't ask me for any kind of more info. Every thing is given in comment section. Guys please please help me.
The only issue i could see in your example is in this line
<script src="/javascripts/application.js" type="text/javascript">
which is looking for this .js and not founding it due to this highlight functions are not getting created.
Try changing it with this and add application.js with different script tag.
<script type="text/javascript">
Working Example
.highlight {
background-color: #fff34d;
-moz-border-radius: 5px; /* FF1+ */
-webkit-border-radius: 5px; /* Saf3-4 */
border-radius: 5px; /* Opera 10.5, IE 9, Saf5, Chrome */
-moz-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.7); /* FF3.5+ */
-webkit-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.7); /* Saf3.0+, Chrome */
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.7); /* Opera 10.5+, IE 9.0 */
}
.highlight {
padding:1px 4px;
margin:0 -4px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery.fn.highlight = function(pat) {
function innerHighlight(node, pat) {
var skip = 0;
if (node.nodeType == 3) {
var pos = node.data.toUpperCase().indexOf(pat);
if (pos >= 0) {
var spannode = document.createElement('span');
spannode.className = 'highlight';
var middlebit = node.splitText(pos);
var endbit = middlebit.splitText(pat.length);
var middleclone = middlebit.cloneNode(true);
spannode.appendChild(middleclone);
middlebit.parentNode.replaceChild(spannode, middlebit);
skip = 1;
}
} else if (node.nodeType == 1 && node.childNodes && !/(script|style) /i.test(node.tagName)) {
for (var i = 0; i < node.childNodes.length; ++i) {
i += innerHighlight(node.childNodes[i], pat);
}
}
return skip;
}
return this.each(function() {
innerHighlight(this, pat.toUpperCase());
});
};
jQuery.fn.removeHighlight = function() {
function newNormalize(node) {
for (var i = 0, children = node.childNodes, nodeCount = children.length; i < nodeCount; i++) {
var child = children[i];
if (child.nodeType == 1) {
newNormalize(child);
continue;
}
if (child.nodeType != 3) { continue; }
var next = child.nextSibling;
if (next == null || next.nodeType != 3) { continue; }
var combined_text = child.nodeValue + next.nodeValue;
new_node = node.ownerDocument.createTextNode(combined_text);
node.insertBefore(new_node, child);
node.removeChild(child);
node.removeChild(next);
i--;
nodeCount--;
}
}
return this.find("span.highlight").each(function() {
var thisParent = this.parentNode;
thisParent.replaceChild(this.firstChild, this);
newNormalize(thisParent);
}).end();
};
</script>
<body>
Search: <input type="text" id="text-search" />
<p>
<b>Demo </b> he new edition of KnowlEdge K12 enables your school with flexibility by wholly automating their administrative and academic processes. With IncTech’s solution for K12 schools, you can. We give you an internal infrastructure so you can share school and student information.
</p>
<script type="text/javascript">
$(function() {
$('#text-search').bind('keyup change', function(ev) {
// pull in the new value
var searchTerm = $(this).val();
// remove any old highlighted terms
$('body').removeHighlight();
// disable highlighting if empty
if ( searchTerm ) {
// highlight the new term
$('body').highlight( searchTerm );
}
});
});
</script>
</body>

javascript game ( 3 in line ) line check logic

i've been in a battle to sort this problem since yesterday and i fear that i've gotten tunnel vision.
The game:
first player to make a line of 3 of a kind (xxx or 000) wins.
http://jsfiddle.net/brunobliss/YANAW/
The catch:
Only the first horizontal line is working!!! I can make it all work using a lot of IFS but repeating the same code over and over again is often a good indicator that i'm doing somethin wrong
The problem:
bruno.checkWin(); will check if there's a line or not, the guy who presented me this game chalenge told me that it is possible to check the lines with a for loop and that i should use it instead of IFS. I can't solve this without IFS unfortunately...
<!doctype html>
<html>
<head>
<meta charset="iso-8859-1">
<title> </title>
<style>
#jogo {
border: #000 1px solid;
width: 150px;
position: absolute;
left: 50%;
top: 50%;
margin-left: -75px;
margin-top: -75px;
}
#jogo div {
display: inline-block;
vertical-align: top;
width: 28px;
height: 28px;
padding: 10px;
font-size: 20px;
border: #000 1px solid;
border-collapse: collapse;
text-align: center;
}
#reset {
font-family: Verdana;
width: 153px;
height: 30px;
background-color: black;
color: white;
text-align: center;
cursor: pointer;
left: 50%;
top: 50%;
position: absolute;
margin-left: -76px;
margin-top: 100px;
}
</style>
<script> </script>
</head>
<body>
<div id="jogo"> </div>
<div id="reset"> RESET </div>
<script>
var ultimo = "0";
var reset = document.getElementById('reset');
var jogo = document.getElementById('jogo');
var cell = jogo.getElementsByTagName('div');
var bruno = {
init: function () {
var jogo = document.getElementById('jogo');
for ( i = 0 ; i < 9 ; i++ ) {
var cell = document.createElement('div');
cell.onclick = function () {
// variavel publica dentro do obj?
ultimo = (ultimo == "x") ? 0 : "x";
this.innerHTML = ultimo;
bruno.checkWin();
};
jogo.appendChild(cell);
}
},
checkWin: function () {
var jogo = document.getElementById('jogo');
var cell = jogo.getElementsByTagName('div');
// as diagonais nao verificar por loop
for ( i = 0 ; i < cell.length ; i=i+4 ) {
switch(i) {
case 0:
if (cell[0].innerHTML != '') {
bruno.checkFirst();
}
case 4:
if (cell[4].innerHTML != '') {
bruno.checkFirst();
}
case 8:
if (cell[8].innerHTML != '') {
bruno.checkFirst();
}
}
/*
} else
if (i == 4 && cell[4].innerHTML != '') {
bruno.checkCenter();
} else
if (i == 8 && cell[8].innerHTML != '') {
bruno.checkLast();
}*/
}
},
reset: function () {
var jogo = document.getElementById('jogo');
var cell = jogo.getElementsByTagName('div');
for ( j = 0 ; j < cell.length ; j++ ) {
cell[j].innerHTML = "";
}
},
checkFirst: function () {
if (cell[0].innerHTML == cell[1].innerHTML && cell[1].innerHTML == cell[2].innerHTML) {
alert("linha horizontal");
return false;
} else
if (cell[0].innerHTML == cell[3].innerHTML && cell[3].innerHTML == cell[6].innerHTML) {
alert("linha vertical");
return false;
}
},
checkMiddle: function () {
// check vertical and horizontal lines from the center
},
checkLast: function () {
// check last horizontal and right edge vertical
}
};
window.onload = function () {
bruno.init();
};
reset.onclick = function () {
bruno.reset();
};
</script>
</body>
</html>
I came up with a more 'compact' version of your code. No switch statements. Have a look:
http://jsfiddle.net/YANAW/1/
Here's the code, for those who prefer to read it here. Important/updated functions are checkWin() and checkCells().
var bruno = {
init: function () {
var jogo = document.getElementById('jogo');
for ( i = 0 ; i < 9 ; i++ ) {
var cell = document.createElement('div');
cell.onclick = function () {
// variavel publica dentro do obj?
ultimo = (ultimo == "x") ? 0 : "x";
this.innerHTML = ultimo;
bruno.checkWin();
};
jogo.appendChild(cell);
}
},
checkWin: function () {
var jogo = document.getElementById('jogo');
var cells = jogo.getElementsByTagName('div');
// Scan through every cell
var numRows = 3;
var numColumns = 3;
for (var i = 0; i < cells.length; i++)
{
// Determine cell's position
var isHorizontalFirstCell = ((i % numColumns) === 0);
var isVerticalFirstCell = (i < numColumns);
var isTopLeftCorner = (i == 0);
var isTopRightCorner = (i == 2);
// Check for horizontal matches
if (isHorizontalFirstCell
&& bruno.checkCells(
cells, i,
(i + 3), 1))
{
alert('Horizontal');
}
// Check for vertical matches
if (isVerticalFirstCell
&& bruno.checkCells(
cells, i,
(i + 7), 3))
{
alert('Vertical');
}
// Check for diagonal matches
if (isTopLeftCorner
&& bruno.checkCells(
cells, i,
(i + 9), 4))
{
alert('Diagonal');
}
if (isTopRightCorner
&& bruno.checkCells(
cells, i,
(i + 5), 2))
{
alert('Diagonal');
}
}
},
reset: function () {
var jogo = document.getElementById('jogo');
var cell = jogo.getElementsByTagName('div');
for ( j = 0 ; j < cell.length ; j++ ) {
cell[j].innerHTML = "";
}
},
checkCells: function(cells, index, limit, step) {
var sequenceChar = null;
for (var i = index; i < limit; i += step)
{
// Return false immediately if one
// of the cells in the sequence is empty
if (!cells[i].innerHTML)
return false;
// If this is the first cell we're checking,
// store the character(s) it holds.
if (sequenceChar === null)
sequenceChar = cells[i].innerHTML;
// Otherwise, confirm that this cell holds
// the same character(s) as the previous cell(s).
else if (cells[i].innerHTML !== sequenceChar)
return false;
}
// If we reached this point, the entire sequence
// of cells hold the same character(s).
return true;
}
};

Categories