Get an attribute from a grid of items - javascript

I have a game board 8x8. below is the code to create the board...
for (var i = 0 ; i < TOTAL_ROWS ; i++) {
tab_imgs[i] = [];
for (var j = 0 ; j < TOTAL_COLUMNS ; j++) {
var num_img = Math.ceil(Math.random() * NUM_IMGS);
if (i > 1) {
while(tab_imgs[i-2][j] == num_img && tab_imgs[i-1][j] == num_img){
num_img = Math.ceil(Math.random() * NUM_IMGS);
}
}
if (j > 1) {
while(tab_imgs[i][j-2] == num_img && tab_imgs[i][j-1] == num_img){
num_img = Math.ceil(Math.random() * NUM_IMGS);
if (i > 1) {
while(tab_imgs[i-2][j] == num_img && tab_imgs[i-1][j] == num_img){
num_img = Math.ceil(Math.random() * NUM_IMGS);
}
}
}
}
tab_imgs[i][j] = num_img;
render_table += '<div class="jewel jewel_' + num_img + '" data-row="' + i + '" data-col="' + j + '" data-jewel="' + num_img + '" style="top: ' + Number(i*TOTAL_IMGS) + 'px; left: ' + Number(j*TOTAL_IMGS) + 'px;"></div>';
}
}
The code above will produce a random board. My issue is when the user resumes an existing game. I need to loop through the ALREADY produced html and grab the attribute "data-jewel" so instead of these lines:
num_img = Math.ceil(Math.random() * NUM_IMGS);
I have:
num_img = attribute('data-jewel')
for each grid;

You can retrieve the value of a data attribute by using the jQuery .data() method:
num_img = +$('.selector').data( 'jewel' );

Related

JavaScript code working only in Chrome but not in Firefox, IE, Opera and Safari

I'n new to programming and I tried something in JavaScript and it worked well in Chrome. But It fails to work in IE, Firefox, Safari and Opera. Am I doing anything wrong with my code?
function hp(form) {
var count1 = 0, count2 = 0, count3 = 0, count4 = 0, count5 = 0, count6 = 0, count7 = 0, count8 = 0, count9 = 0, count10 = 0;
for (var i = 0; i < 3; i++) {
if (form.q1[i].checked == true) {
count1++;
}
}
if (count1 !== 1) {
alert("Please Answer 1st Question");
return false;
}
for (var i = 0; i < 3; i++) {
if (form.q2[i].checked == true) {
count2++;
}
}
if (count2 !== 1) {
alert("Please Answer 2nd Question");
return false;
}
for (var i = 0; i < 3; i++) {
if (form.q3[i].checked == true) {
count3++;
}
}
if (count3 !== 1) {
alert("Please Answer 3rd Question");
return false;
}
for (var i = 0; i < 3; i++) {
if (form.q4[i].checked == true) {
count4++;
}
}
if (count4 !== 1) {
alert("Please Answer 4th Question");
return false;
}
for (var i = 0; i < 3; i++) {
if (form.q5[i].checked == true) {
count5++;
}
}
if (count5 !== 1) {
alert("Please Answer 5th Question");
return false;
}
for (var i = 0; i < 3; i++) {
if (form.q6[i].checked == true) {
count6++;
}
}
if (count6 !== 1) {
alert("Please Answer 6th Question");
return false;
}
for (var i = 0; i < 3; i++) {
if (form.q7[i].checked == true) {
count7++;
}
}
if (count7 !== 1) {
alert("Please Answer 7th Question");
return false;
}
for (var i = 0; i < 3; i++) {
if (form.q8[i].checked == true) {
count8++;
}
}
if (count8 !== 1) {
alert("Please Answer 8th Question");
return false;
}
for (var i = 0; i < 4; i++) {
if (form.q9[i].checked == true) {
count9++;
}
}
if (count9 !== 1) {
alert("Please Answer 9th Question");
return false;
}
for (var i = 0; i < 3; i++) {
if (form.q10[i].checked == true) {
count10++;
}
}
if (count10 !== 1) {
alert("Please Answer 10th Question");
return false;
}
answer1 = (form.q1.value);
answer2 = (form.q2.value);
answer3 = (form.q3.value);
answer4 = (form.q4.value);
answer5 = (form.q5.value);
answer6 = (form.q6.value);
answer7 = (form.q7.value);
answer8 = (form.q8.value);
answer9 = (form.q9.value);
answer10 = (form.q10.value);
var a = parseInt(answer1);
var b = parseInt(answer2);
var c = parseInt(answer3);
var d = parseInt(answer4);
var e = parseInt(answer5);
var f = parseInt(answer6);
var g = parseInt(answer7);
var h = parseInt(answer8);
var ii = parseInt(answer9);
var j = parseInt(answer10);
var c = a + b + c + d + e + f + g + h + ii + j;
//document.getElementById("result").innerHTML= "The selected values are "+"</br>"+a+"</br>"+b+c+d+e+f+g+h+ii+j+"</br>"+c;
if (c <= 20) {
document.getElementById("total").innerHTML = "<h3>" + "ABCD" + "</h3>" + "</br>" + "<IMG ALIGN='center' " + "SRC='images/img.png'>";
}
else if ((c > 20) && (c <= 25)) {
document.getElementById("total").innerHTML = "<h3>" + "ABCD" + "</h3>" + "</br>" + "<IMG ALIGN='center' " + "SRC='images/img.png'>";
}
else if ((c > 25) && (c <= 30)) {
document.getElementById("total").innerHTML = "<h3>" + "ABCD" + "</h3>" + "</br>" + "<IMG ALIGN='center' " + "SRC='images/img.png'>";
}
else if ((c > 30) && (c <= 40)) {
document.getElementById("total").innerHTML = "<h3>" + "ABCD" + "</h3>" + "</br>" + "<IMG ALIGN='center' " + "SRC='images/img.png'>";
}
else if ((c > 40) && (c <= 50)) {
document.getElementById("total").innerHTML = "<h3>" + "ABCD" + "</h3>" + "</br>" + "<IMG ALIGN='center' " + "SRC='images/img.png'>";
}
else if ((c > 50) && (c <= 60)) {
document.getElementById("total").innerHTML = "<h3>" + "ABCD" + "</h3>" + "</br>" + "<IMG ALIGN='center' " + "SRC='images/img.png'>";
}
else if ((c > 60) && (c <= 65)) {
document.getElementById("total").innerHTML = "<h3>" + "ABCD" + "</h3>" + "</br>" + "<IMG ALIGN='center' " + "SRC='images/img.png'>";
}
else if ((c > 65) && (c <= 75)) {
document.getElementById("total").innerHTML = "<h3>" + "ABCD" + "</h3>" + "</br>" + "<IMG ALIGN='center' " + "SRC='images/img.png'>";
}
else if ((c > 75) && (c <= 90)) {
document.getElementById("total").innerHTML = "<h3>" + "ABCD" + "</h3>" + "</br>" + "<IMG ALIGN='center' " + "SRC='images/img.png'>";
}
c = 0;
}
I tried this code in local host and i got my desired output in Google Chrome. When i tried the same page in Firefox and other browser, it failed to work. Only checkbox validation is working fine.
Thanks in Advance
From personal experience, I have noticed that Chrome is more forgiving when it comes to small errors. It is strange how you are not getting an error in the debug box at all...
But, a place I can see from reading the code is where you define the variables a,b,c... I recommend placing a comma after each. So, you get:
var a = parseInt(answer1),
b = parseInt(answer2),
c = parseInt(answer3),
d = parseInt(answer4),
e = parseInt(answer5),
f = parseInt(answer6),
g = parseInt(answer7),
h = parseInt(answer8),
ii = parseInt(answer9),
j = parseInt(answer10);
Then here is where I think you have an error. You have var c = ... again after already defining c. So, try removing the var right there.

EaselJS grid drawing is strangely offset/scaled

This code is supposed to draw a grid (it's meant for a maze, so I need to only draw parts of it):
function drawMaze() {
for (var r = 0; r < Rows.length; r++) {
var row = Rows[r];
var sr = new createjs.Shape();
sr.x = 0;
sr.y = (r + 1) * offY;
var gr = sr.graphics.beginStroke("black");
gr.moveTo(0, (r + 1) * offY);
for (var i = 0; i < row.length; i++) {
if (row[i] === true) {
console.log("r=" + r + ",i=" + i + ",x=" + (i + 1) * offX + ",y=" + (r + 1) * offY);
gr.lineTo((i + 1) * offX, (r + 1) * offY);
} else {
gr.moveTo((i + 1) * offX, (r + 1) * offY);
}
}
stage.addChild(sr);
}
for (var c = 0; c < Cols.length; c++) {
var col = Cols[c];
var sc = new createjs.Shape();
sc.x = (c + 1) * offX;
sc.y = 0;
var gc = sc.graphics.beginStroke("black");
gc.moveTo((c + 1) * offX, 0);
for (var i = 0; i < col.length; i++) {
if (col[i] === true) {
console.log("c=" + c + ",i=" + i + ",x=" + (c + 1) * offX + ",y=" + (i + 1) * offY);
gc.lineTo((c + 1) * offX, (i + 1) * offY);
} else {
gc.moveTo((c + 1) * offX, (i + 1) * offY);
}
}
stage.addChild(sc);
}
var sd = new createjs.Shape();
sd.graphics.s("black").mt(0, 0).lt(offX * Cols.length, offY * Rows.length).f("red").r(175,175,175,175);
stage.addChild(sd);
stage.update();
}
The diagonal line/red square is only for visualization.
With this, the spacing between rows/columns is doubled and so only half of the lines form a grid. Here is the full code: http://jsfiddle.net/vyLRT/9/
I just found out what was wrong! I just simply moved the lines twice.
So instead of
sr.x = 0;
sr.y = (r + 1) * offY;
sc.x = (c + 1) * offX;
sc.y = 0;
all values just need to be set to 0.

Pagination not working :

I am displaying pagination in my application using following javascript,its working fine for me, but i need to break the pagination after 5 pages
This is my existing pagination
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
but i need to display the pagination by following
1 2 3 4 5 ......15 16 17 18 19 20
if i click on page number 5 then it should add another 5 pages to current page
My Javscript like this
<script type="text/javascript">
function Pager(tableName, itemsPerPage) {
this.tableName = tableName;
this.itemsPerPage = itemsPerPage;
this.currentPage = 1;
this.pages = 0;
this.inited = false;
this.showRecords = function(from, to) {
var rows = document.getElementById(tableName).rows;
// i starts from 1 to skip table header row
for (var i = 1; i < rows.length; i++) {
if (i < from || i > to)
rows[i].style.display = 'none';
else
rows[i].style.display = '';
}
}
this.showPage = function(pageNumber) {
if (! this.inited) {
alert("not inited");
return;
}
var oldPageAnchor = document.getElementById('pg'+this.currentPage);
oldPageAnchor.className = 'pg-normal';
this.currentPage = pageNumber;
var newPageAnchor = document.getElementById('pg'+this.currentPage);
newPageAnchor.className = 'pg-selected';
var from = (pageNumber - 1) * itemsPerPage + 1;
var to = from + itemsPerPage - 1;
this.showRecords(from, to);
}
this.prev = function() {
if (this.currentPage > 1)
this.showPage(this.currentPage - 1);
}
this.next = function() {
if (this.currentPage < this.pages) {
this.showPage(this.currentPage + 1);
}
}
this.init = function() {
var rows = document.getElementById(tableName).rows;
var records = (rows.length - 1);
this.pages = Math.ceil(records / itemsPerPage);
this.inited = true;
}
this.showPageNav = function(pagerName, positionId) {
if (! this.inited) {
alert("not inited");
return;
}
var element = document.getElementById(positionId);
var pagerHtml = '<span onclick="' + pagerName + '.prev();" class="pg-normal"> <img src="${ctx}/images/prev.PNG" alt=" « Prev" height="17px" width="26px" style="vertical-align: middle;"/> </span> ';
for (var page = 1; page <= this.pages; page++)
pagerHtml += '<span id="pg' + page + '" class="pg-normal" onclick="' + pagerName + '.showPage(' + page + ');">' + page + '</span> ';
pagerHtml += '<span onclick="'+pagerName+'.next();" class="pg-normal"> <img src="${ctx}/images/nexts.png" alt="Next »" height="17px" width="26px" style="vertical-align: middle;"/></span>';
element.innerHTML = pagerHtml;
}
}
</script>
if any suggestion it will be appreciable
here is the JSfiddle
Here is a new jsfiddle doing what you want to do:
http://jsfiddle.net/nye7a/2/
The showPageNav function has been changed like this :
this.showPageNav = function(pagerName, positionId) {
var pageIndex = this.currentPage,
pageCount = this.pages,
start = Math.max(1, pageIndex - 4),
end = Math.min(pageCount, pageIndex + 4),
start2 = pageCount-4,
end2 = pageCount;
if (start2 <= end)
end = pageCount;
if (! this.inited) {
alert("not inited");
return;
}
var element = document.getElementById(positionId);
var pagerHtml = '';
// adds the Prev button only if needed
if (pageIndex > 1)
pagerHtml = '<span onclick="' + pagerName + '.prev();" class="pg-normal"> « Prev </span> ';
// paging from 1 to 5
for (var page = start; page <= end; page++) {
pagerHtml += '<span id="pg' + page + '" class="pg-normal" onclick="' + pagerName + '.showPage(' + page + ');">' + page + '</span> ';
}
// paging from pageCount-5 to pageCount
if (end != pageCount) {
pagerHtml += '<span>...</span>';
for (var page = start2; page <= end2; page++) {
pagerHtml += '<span id="pg' + page + '" class="pg-normal" onclick="' + pagerName + '.showPage(' + page + ');">' + page + '</span> ';
}
}
// adds the Next button only if needed
if (pageIndex < pageCount && pageCount > 1)
pagerHtml += '<span onclick="'+pagerName+'.next();" class="pg-normal"> Next »</span>';
element.innerHTML = pagerHtml;
}

Why won't my Javascript function be called with the onLoad event?

I was trying to test my code...but I can't get any Javascript function to be called. I've tried a lot of things: Making buttons to call my existing function, trying to call new functions in with this code, inserting my function into previously successful HTML files. None of these strategies have worked. Whatever I do, any Javascript function in this file will not be called, or appears to not be called. I have no idea why.
<!DOCTYPE html>
<html>
<head>
<title>Template Page</title>
</head>
<body onLoad="chooser()">
<!--HTML "route" for images-->
<img src="IMG_0000.jpg"></img>
<img src="IMG_0001.jpg"></img>
<img src="IMG_0002.jpg"></img>
<img src="IMG_0003.jpg"></img>
<img src="IMG_0004.jpg"></img>
<script type="text/javascript">
//Create a list of images, choose randomly for that list (to display on the page), and then delete that image from the list
function chooser()
{
//Declare variables
var start = 0;
var end = 9;
var images = [];
var imageNumber = start;
var imageName = "";
//Add image src's to array
while (imageNumber <= end)
{
if (imageNumber < 10)
{
imageName = "IMG_000" + string(imageNumber) + ".jpg";
}
else if (imageNumber > 9) && (imageNumber < 100)
{
imageName = "IMG_00" + string(imageNumber) + ".jpg";
}
else if (imageNumber > 99) && (imageNumber < 1000)
{
imageName = "IMG_0" + string(imageNumber) + ".jpg";
}
else if (imageNumber > 999) && (imageNumber < 10000)
{
imageName = "IMG_" + string(imageNumber) + ".jpg";
}
images.push(imageName);
imageNumber = imageNumber + 1;
alert(images);
}
}
</script>
</body>
</html>
You have syntax error in your else-if parts, here's the correct one:
if (imageNumber < 10)
{
imageName = "IMG_000" + string(imageNumber) + ".jpg";
}
else if ((imageNumber > 9) && (imageNumber < 100))
{
imageName = "IMG_00" + string(imageNumber) + ".jpg";
}
else if ((imageNumber > 99) && (imageNumber < 1000))
{
imageName = "IMG_0" + string(imageNumber) + ".jpg";
}
else if ((imageNumber > 999) && (imageNumber < 10000))
{
imageName = "IMG_" + string(imageNumber) + ".jpg";
}
and also that function-like string(), what do you want with them? Convert imageNumber from integer to string? In that case, you don't need anything. "+" operator will automatically convert the numbers to string. So remove those string() making your final code to:
if (imageNumber < 10)
{
imageName = "IMG_000" + imageNumber + ".jpg";
}
else if ((imageNumber > 9) && (imageNumber < 100))
{
imageName = "IMG_00" + imageNumber + ".jpg";
}
else if ((imageNumber > 99) && (imageNumber < 1000))
{
imageName = "IMG_0" + imageNumber + ".jpg";
}
else if ((imageNumber > 999) && (imageNumber < 10000))
{
imageName = "IMG_" + imageNumber + ".jpg";
}

Javascript Hanging UI on IE6/7

Could anyone suggest performance improvements for the function I've written (below, javascript with bits of jquery)? Or point out any glaring, basic flaws? Essentially I have a javascript Google map and a set of list based results too, and the function is fired by a checkbox click, which looks at the selection of checkboxes (each identifying a 'filter') and whittles the array data down accordingly, altering the DOM and updating the Google map markers according to that. There's a 'fake' loader image in there too at the mo that's just on a delay so that it animates before the UI hangs!
function updateFilters(currentCheck) {
if (currentCheck == undefined || (currentCheck != undefined && currentCheck.disabled == false)) {
var delay = 0;
if(document.getElementById('loader').style.display == 'none') {
$('#loader').css('display', 'block');
delay = 750;
}
$('#loader').delay(delay).hide(0, function(){
if (markers.length > 0) {
clearMarkers();
}
var filters = document.aspnetForm.filters;
var markerDataArray = [];
var filterCount = 0;
var currentfilters = '';
var infoWindow = new google.maps.InfoWindow({});
for (i = 0; i < filters.length; i++) {
var currentFilter = filters[i];
if (currentFilter.checked == true) {
var filtername;
if (currentFilter.parentNode.getElementsByTagName('a')[0].textContent != undefined) {
filtername = currentFilter.parentNode.getElementsByTagName('a')[0].textContent;
} else {
filtername = currentFilter.parentNode.getElementsByTagName('a')[0].innerText;
}
currentfilters += '<li>' + $.trim(filtername) +
$.trim(document.getElementById('remhide').innerHTML).replace('#"','#" onclick="toggleCheck(\'' + currentFilter.id + '\');return false;"');
var nextFilterArray = [];
filterCount++;
for (k = 0; k < filterinfo.length; k++) {
var filtertype = filterinfo[k][0];
if (filterinfo[k][0] == currentFilter.id) {
var sitearray = filterinfo[k][1];
for (m = 0; m < sitearray.length; m++) {
var thissite = sitearray[m].split(',');
if (filterCount > 1) {
nextFilterArray.push(thissite[2] + '|' + thissite[1]
+ '|' + thissite[0]);
} else {
markerDataArray.push(thissite[2] + '|' + thissite[1]
+ '|' + thissite[0]);
}
}
}
}
if (filterCount > 1) {
var itemsToRemove = [];
for (j = 0; j < markerDataArray.length; j++) {
var exists = false;
for (k = 0; k < nextFilterArray.length; k++) {
if (markerDataArray[j] == nextFilterArray[k]) {
exists = true;
}
}
if (exists == false) {
itemsToRemove.push(j);
}
}
var itemsRemoved = 0;
for (j = 0; j < itemsToRemove.length; j++) {
markerDataArray.splice(itemsToRemove[j]-itemsRemoved,1);
itemsRemoved++;
}
}
}
}
if (currentfilters != '') {
document.getElementById('appliedfilters').innerHTML = currentfilters;
document.getElementById('currentfilters').style.display = 'block';
} else {
document.getElementById('currentfilters').style.display = 'none';
}
if (filterCount < 1) {
for (j = 0; j < filterinfo.length; j++) {
var filtertype = filterinfo[j][0];
if (filterinfo[j][0] == 'allvalidsites') {
var sitearray = filterinfo[j][1];
for (m = 0; m < sitearray.length; m++) {
var thissite = sitearray[m].split(',');
markerDataArray.push(thissite[2] + '|' + thissite[1]
+ '|' + thissite[0]);
}
}
}
}
var infoWindow = new google.maps.InfoWindow({});
var resultHTML = '<div id="page1" class="page"><ul>';
var count = 0;
var page = 1;
var paging = '<li class="selected">1</li>';
for (i = 0; i < markerDataArray.length; i++) {
var markerInfArray = markerDataArray[i].split('|');
var url = '';
var name = '';
var placename = '';
var region = '';
var summaryimage = 'images/controls/placeholder.gif';
var summary = '';
var flag = 'images/controls/placeholderf.gif';
for (j = 0; j < tsiteinfo.length; j++) {
var thissite = tsiteinfo[j].split('|');
if (thissite[0] == markerInfArray[2]) {
name = thissite[1];
placename = thissite[2];
region = thissite[3];
if (thissite[4] != '') {
summaryimage = thissite[4];
}
summary = thissite[5];
if (thissite[6] != '') {
flag = thissite[6];
}
}
}
for (k = 0; k < sitemapperinfo.length; k++) {
var thissite = sitemapperinfo[k].split('|');
if (thissite[0] == markerInfArray[2]) {
url = thissite[1];
}
}
var markerLatLng = new google.maps.LatLng(markerInfArray[1].toString(), markerInfArray[0].toString());
var infoWindowContent = '<div class="infowindow">' + markerInfArray[2] + ': ';
var siteurl = approot + '/sites/' + url;
infoWindowContent += '<strong>' + name + '</strong>';
infoWindowContent += '<br /><br/><em>' + placename + ', ' + region + '</em></div>';
marker = new google.maps.Marker({
position: markerLatLng,
title: $("<div/>").html(name).text(),
shadow: shadow,
icon: image
});
addInfo(infoWindow, marker, infoWindowContent);
markers.push(marker);
count++;
if ((count > 20) && ((count % 20) == 1)) { // 20 per page
page++;
resultHTML += '</ul></div><div id="page' + page + '" class="page"><ul>';
paging += '<li>' + page + '</li>';
}
resultHTML += '<li><div class="namehead"><h2>' + name + ' <span>' + placename + ', ' + region + '</span></h2></div>' +
'<div class="codehead"><h2><img alt="' + region + '" src="' + approot +
'/' + flag + '" /> ' + markerInfArray[2] + '</h2></div>' +
'<div class="resultcontent"><img alt="' + name + '" src="' + approot +
'/' + summaryimage +'" />' + '<p>' + summary + '</p>' + document.getElementById('buttonhide').innerHTML.replace('#',siteurl) + '</div></li>';
}
$('#filteredmap .paging').each(function(){
$(this).html(paging);
});
document.getElementById('resultslist').innerHTML = resultHTML + '</ul></div>';
document.getElementById('count').innerHTML = count + ' ';
document.getElementById('page1').style.display = 'block';
for (t = 0; t < markers.length; t++) {
markers[t].setMap(filteredMap);
}
});
}
}
function clearMarkers() {
for (i = 0; i < markers.length; i++) {
markers[i].setMap(null);
markers[i] = null;
}
markers.length = 0;
}
However, I'm suffering from performance issues (UI hanging) specifically in IE6 and 7 when the number of results is high, but not in any other modern browsers, i.e. FF, Chrome, Safari etc. It is much worse when the Google map markers are being created and added (if I remove this portion it is still slugglish, but not to the same degree). Can you suggest where I'm going wrong with this?
Thanks in advance :) Please be gentle if you can, I don't do much javascript work and I'm pretty new to it and jquery!
This looks like a lot of work to do at the client no matter what.
Why don't you do this at the server instead, constructing all the HTML there, and just refresh the relevant sections with the results of an ajax query?

Categories

Resources