I am using JavaScript for loop, my code is here
content = "";
for (var i = 0; i < 13; i++) {
var alt=glevel[i].getAttribute("name");
if(jQuery.inArray(alt, clickArray) > -1) {
if ($.browser.msie && parseInt($.browser.version, 10) === 8 || $.browser.msie && parseInt($.browser.version, 10) === 7) {
content += "<li id='"+alt+"' style='cursor:pointer;filter:alpha(opacity=50);'>"+alt+"<br><div style='width:auto;'><img src='products/"+alt+".png'><br><font size='1px'>Click Base To Select</font></div><br><p style='text-decoration:none;color:#ffffff;font-size:10px;margin-top:-18px;' id='"+alt+"'>Click Here For Product Info</p></li> \n";
} else {
content += "<li id='"+alt+"' style='cursor:pointer;opacity:0.3;'>"+alt+"<br><div style='width:auto;'><img src='products/"+alt+".png'><br><font size='1px'>Click Base To Select</font></div><br><p style='text-decoration:none;color:#ffffff;font-size:10px;margin-top:-18px;' id='"+alt+"'>Click Here For Product Info</p></li> \n";
}
//$('#'+clickArray[alt]+"").css("opacity","0.5");
} else{
content += "<li id='"+alt+"' style='cursor:pointer'>"+alt+"<br><div style='width:auto;'><img src='products/"+alt+".png'><br><font size='1px'></font></div><br><p style='text-decoration:none;color:#ffffff;font-size:10px;margin-top:-18px;' id='"+alt+"'></p></li> \n";
}
$("#step_2").html(content);
}
output of this code is something like that :-
image1 image2 image3 image4
image5 image6
image7 image8 image9 image10
image11 image12 image13
update:- it looks like that because of my table width and height
It works very fine, it display the real product images what i have.
now i want to display something like this :-
image1 image2 image3 image4
image5 image6 image7
image8 image9 image10
image11 image12 image13
means in the first row 4 images, while 2nd,3rd, and 4th row have 3 images
for (var i = 0; i < 13; i++) {
content += "...";
if (i == 3) // after the fourth line,
content += '<br/><br/>'; // add an empty line
if (i > 3 && (i - 4) % 3 == 2) // then, after every three lines
content += '<br/><br/>'; // add an empty line
}
This is could do the trick:
var content = "", imgNum = 1, max = 4;
for (var i = 0; i < 4; i++) {
if (i != 0) {
max = 3;
}
for (var j = 0; j < max; j++) {
content += "image" + imgNum;
imgNum++;
}
content += "<br />";
}
document.write(content);
demo
This is the logic:
set starting image number to 1
set max to 4 (later we will change it to 3)
loop the num of rows (4 times)
if we are at the first loop, leave max 4, otherwise change it to 3
loop the num of cols (max times)
add stuff to content
increase image number by 1
add the break after the loop
I prefered to use two loops instead of using the % operator, because it is more readable and faster.
edit: If you don't care about performance, I found a way to make a readable version with the %:
var content="";
for (var i = 0; i < 13; i++){
content += "image"+(i+1);
if(i==0||i==12){
continue;
}
if(i%3==0) {
content += "<br />";
}
}
document.write(content);
put this at the end of loop:
if (i == 3) { content += '<br/>'; }
if (i > 3 && (i - 4) % 3 == 2) { content += '<br/>'; }
What about this?
for (var i = 0; i < 13; i++){
content += "<li>...</li>";
if(i==3 || i==6 || i==9) { content += "<br />"; }
}
Related
I hope anyone familiar with jQuery Reel Plugin can help me.
I have a table that dynamically loads images and on those images is an onclick function that is supposed to change the reel image to the corresponding cell item. The sprite is not changing away from the default one that is hard-coded.
I understand vaguely that I have to initialize the dynamic images with the "reel" class, but adding the attribute class="reel" doesn't do anything.
There is another question asking
the same thing
-- but I don't know jQuery and don't know how to apply the answer to my own project.
function previewIt(item) {
var reel = document.getElementById("previewReel");
reel.dataset.image = item.id + "sprite.png";
}
function headCatalogLoader() {
var table = document.getElementById("headCatalog");
var img = 2;
var uID = 8;
for (var i = 0; i <= 2; i++) {
var row = table.insertRow(i);
for (var k = 0; k <= 2; k++) { // 2 is because 3 columns
var skinTone = "none";
var cell = row.insertCell(k);
if (k == 0) {
skinTone = "lgt";
}
else if (k == 1) {
skinTone = "med";
}
else if (k == 2) {
skinTone = "drk";
}
cell.innerHTML = "<img src=\"headimgs/head" + skinTone + img + ".png\" id=\"head" + uID + skinTone + "\" onclick=\"previewIt(this)\" class=\"reel\">";
uID--;
}
img--;
}
}
<script src="http://test.vostrel.net/jquery.reel/jquery.reel.js" type="text/javascript"></script>
<div id="headPreview">
<img src="head1med.png" height="800"
id="previewReel"
class="reel"
data-image="head1medsprite.png"
data-frames="8"
data-footage="4">
</div>
I apologize if the code makes you cringe. If it's at all possible I'd like to do it purely in JavaScript, if not then a brief explanation would really help me out. Thank you friends.
Requirement :
You have a table, showing image dynamically
You want to apply reel only on image id="previewReel" when user click on the image from dynamically loaded images
Solution :
You need to change main image #previewReel reel image runtime.
$("#previewReel").reel("image", $(item).attr('src'));
Check below:
headCatalogLoader();
function headCatalogLoader() {
var table = document.getElementById("headCatalog");
var img = 2;
var uID = 8;
for (var i = 0; i <= 2; i++) {
var row = table.insertRow(i);
for (var k = 0; k <= 2; k++) { // 2 is because 3 columns
var skinTone = "none";
var cell = row.insertCell(k);
if (k == 0) {
skinTone = "lgt";
}
else if (k == 1) {
skinTone = "med";
}
else if (k == 2) {
skinTone = "drk";
}
cell.innerHTML = "<img src=\"https://picsum.photos/200/200/?image=65" + uID + "\" id=\"head" + uID + skinTone + "\" onclick=\"previewIt(this)\" \>";
uID--;
}
img--;
}
}
function previewIt(item) {
$("#previewReel").reel("image", $(item).attr('src')); ///this line will apply new reel
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://code.vostrel.cz/jquery.reel.js" type="text/javascript"></script>
<div id="headPreview">
<img src="https://picsum.photos/200/200" width="210" height="186"
id="previewReel"
class="reel"
data-image="https://picsum.photos/200/200"
data-frames="8"
data-footage="4"
data-revolution="800"
/>
</div>
<br><br>
<ul>
<li>Runtime table image loaded:</li>
<li>Click on any image, to load its reel effect above</li>
</ul>
<table id="headCatalog"></table>
I am coding an adventure game and have a primitive sortInventory() function. It cycles through the player.inventory array and displays each item in its own <div>. I want to surround the entire completed 'inventory' with a <div class="inv"> - here are the functions:
function sortInventory() {
var rowCount = 0;
var firstRowDone = false;
for(var i = 0; i < player.inventory.length; i++) {
rowCount++;
if(rowCount == 6 && firstRowDone == false) {
firstRowDone = true;
rowCount = 0;
dock.innerHTML += "<br>"
}
if(rowCount == 5 && firstRowDone) {
dock.innerHTML += "<br>"
rowCount = 0;
}
dock.innerHTML += "<div class='inv-item'><img class='inv-img' src='" + player.inventory[i].img + "'></img></div>";
}
}
function showInventory() {
dock.innerHTML = "<div class='inv'>";
sortInventory();
dock.innerHTML += "</div>"
}
This currently outputs:
<div class="inv"></div>
<div class="inv-item">..</div>
<div class="inv-item">..</div>
<!-- and so on -->
But I would like it to output:
<div class="inv">
<div class="inv-item">..</div>
<div class="inv-item">..</div>
<!-- and so on -->
</div>
How could I get it to achieve this and why does it close the tag early? Thanks in advance.
Instead of trying to write it in pieces, store it in a variable and write it all at once.
function sortInventory() {
var rowCount = 0;
var invList = '';
for(var i = 0; i < player.inventory.length; i++) {
rowCount++;
if(rowCount == 6 && firstRowDone == false) {
firstRowDone = true;
rowCount = 0;
dock.innerHTML += "<br>"
}
if(rowCount == 5 && firstRowDone) {
dock.innerHTML += "<br>"
rowCount = 0;
}
invList += "<div class='inv-item'><img class='inv-img' src='" + player.inventory[i].img + "'></img></div>";
}
return invList;
}
function showInventory() {
dock.innerHTML = "<div class='inv'>" + sortInventory() + "</div>";
}
This is happening because an open tag cannot live within the DOM without a close tag, with few exceptions like <br /> which is still valid as <br >, so most browsers will try to compensate for this and write the close tag for you.
In short, writing incrementally into the innerHTML tag is always a bad idea and will lead to unexpected results as most all browsers will try to correct it.
Using innerHTML can be cumbersome, not to mention (at times) dangerous. Instead, I would use the document.createElement and Node.appendChild methods.
function sortInventory() {
var rowCount = 0;
var inv = document.createElement('div');
inv.classList.add('inv');
for(var i = 0; i < player.inventory.length; i++) {
rowCount++;
if(rowCount == 6 && firstRowDone == false) {
firstRowDone = true;
rowCount = 0;
inv.appendChild(document.createElement('br'));
}
if(rowCount == 5 && firstRowDone) {
inv.appendChild(document.createElement('br'));
rowCount = 0;
}
var invItem = document.createElement('div');
invItem.classList.add('inv-item');
var invImg = document.createElement('img');
invImg.classList.add('inv-img');
invImg.setAttribute('src', player.inventory[i].img);
invItem.appendChild(invImg);
inv.appendChild(invItem);
}
dock.appendChild(inv);
}
function showInventory() {
sortInventory();
}
I think it closes the tag prematurely because the value received by .innerHTML removes all of the element's descendants and replaces them with nodes constructed by parsing the HTML given in the string. With constructed nodes, it means (in this case) if there is any unclosed tag, it will close it first (so it is a constructed node).
So in order to solve this, first build the string, and finally use the innerHTML in order to set the built value.
Following your logic, it would be something like this:
var newHtml = "";
function sortInventory() {
var rowCount = 0;
for(var i = 0; i < player.inventory.length; i++) {
rowCount++;
if(rowCount == 6 && firstRowDone == false) {
firstRowDone = true;
rowCount = 0;
newHtml += "<br>"
}
if(rowCount == 5 && firstRowDone) {
newHtml += "<br>"
rowCount = 0;
}
newHtml += "<div class='inv-item'><img class='inv-img' src='" + player.inventory[i].img + "'></img></div>";
}
}
function showInventory() {
newHtml = "<div class='inv'>";
sortInventory();
newHtml += "</div>"
dock.innerHTML = newHtml;
}
In order to create a wrapper element with the class .inv around the elements with .inv-item classes, construct the HTML content at a string in the sortInventory function, then return as the content to use, when setting the dock element's innerHTML:
var boxIcon = 'https://image.flaticon.com/icons/svg/122/122186.svg';
var player = {
inventory: [
{img: boxIcon},
{img: boxIcon},
{img: boxIcon}
]
};
var dock = document.getElementById('dock');
function sortInventory(inv) {
var rowCount = 0;
var content = ''
for (var i = 0; i < player.inventory.length; i++) {
rowCount++;
if (rowCount == 6 && firstRowDone == false) {
firstRowDone = true;
rowCount = 0;
content += "<br>"
}
if (rowCount == 5 && firstRowDone) {
content += "<br>"
rowCount = 0;
}
content += "<div class='inv-item'><img class='inv-img' width='32px' src='" + player.inventory[i].img + "'></img></div>";
}
return content;
}
function showInventory() {
dock.innerHTML = "<div class='inv'>" + sortInventory() + "</div>";
}
showInventory();
.inv {
background: #CCC;
}
<div id="dock"></div>
Credits to Flaticon
You could first create the item with the class "inv" and then get it by class name with document.getElementByClassName("inv") and then add with a forloop document.getElementByClassName("inv").innerHtml += <div class="inv-item">..<div>
Construct the HTML string completely then assign to innerHTML of the div, instead of assigning innerHTML 3 times.
Change sortInventory function to return string, append all the string and assign it as innerHTML at once.
I'm trying to show a pyramid of stars in an output tag and I can't get a new line to appear after every row? The output tag has id "result" and i can get the error messages to work if a user doesnt insert a number.
function teken(){
var resultaat =document.getElementById("result");
document.getElementById("result").innerText = "";
if(isNaN(getal.value)){
document.getElementById("result").innerText = "Een GETAL als ingave aub";
} else if(getal.value>10 || getal.value<2){
document.getElementById("result").innerText = "Getal moet groter dan 2 en kleiner dan 10 zijn"
} else {
for(var i = 1; i<= getal.value; i++){
for(var j = 1 ; j<=i;j++){
resultaat.value += "*";
}
resultaat.innerHTML += "<br>"
}
}
Thanks in advance!
Per my comment above, I think you just need resultaat.innerHTML += "*" instead of .value. Here's a trimmed down version of your code (with that edit) that works:
var resultaat = document.getElementById("result");
var n = 5;
for (var i = 1; i <= n; i++) {
for (var j = 1; j <= i; j++) {
resultaat.innerHTML += "*";
}
resultaat.innerHTML += "<br>"
}
<div id="result"></div>
When I type in a non-resizeable text area something like hello world, this is a demo and the text area is small enough, it will look like this:
hello world,
this is a demo
This is not caused by a \n or something.
How can I detect this natural line break in a text area?
A fiddle can be found here: http://jsfiddle.net/yx6B7/
As you can see, there is a line break, but javascript just says that it's one big line without any line-breaks in it.
Finally I found this script on the internet:
function ApplyLineBreaks(strTextAreaId) {
var oTextarea = document.getElementById(strTextAreaId);
if (oTextarea.wrap) {
oTextarea.setAttribute("wrap", "off");
}
else {
oTextarea.setAttribute("wrap", "off");
var newArea = oTextarea.cloneNode(true);
newArea.value = oTextarea.value;
oTextarea.parentNode.replaceChild(newArea, oTextarea);
oTextarea = newArea;
}
var strRawValue = oTextarea.value;
oTextarea.value = "";
var nEmptyWidth = oTextarea.scrollWidth;
var nLastWrappingIndex = -1;
for (var i = 0; i < strRawValue.length; i++) {
var curChar = strRawValue.charAt(i);
if (curChar == ' ' || curChar == '-' || curChar == '+')
nLastWrappingIndex = i;
oTextarea.value += curChar;
if (oTextarea.scrollWidth > nEmptyWidth) {
var buffer = "";
if (nLastWrappingIndex >= 0) {
for (var j = nLastWrappingIndex + 1; j < i; j++)
buffer += strRawValue.charAt(j);
nLastWrappingIndex = -1;
}
buffer += curChar;
oTextarea.value = oTextarea.value.substr(0, oTextarea.value.length - buffer.length);
oTextarea.value += "\n" + buffer;
}
}
oTextarea.setAttribute("wrap", "");
document.getElementById("pnlPreview").innerHTML = oTextarea.value.replace(new RegExp("\\n", "g"), "<br />");
}
Which is working fine.
This isn't a javascript problem.
Look at the word-wrap, white-space and overflow css properties.
The code below came as an included file with a beginner puzzle app tutorial I'm working through. The code works, however now that I've completed the tutorial, I'm trying to read through the files that came preloaded which were not explained.
I'm really tripped up over the "spacecount" variable, and what exactly it's doing. Can anyone comment each line in plain english, so that I can better understand how exactly the code below is populating the rowCount array. Thank you so much.
var totalRows = puzzle.length;
var totalCols = puzzle[0].length;
/* Loop through the rows to create the rowCount array
containing the totals for each row in the puzzle */
var rowCount = [];
for (var i = 0; i < totalRows; i++) {
rowCount[i]="";
spaceCount = 0;
for (var j = 0; j < totalCols; j++) {
if (puzzle[i][j] == "#") {
spaceCount++;
if (j == totalCols-1) rowCount[i] += spaceCount + " ";
} else {
if (spaceCount > 0) {
rowCount[i] += spaceCount + " ";
spaceCount = 0;
}
}
}
Here's a slightly more legible version:
var totalRows = puzzle.length;
var totalCols = puzzle[0].length;
/* Loop through the rows to create the rowCount array
containing the totals for each row in the puzzle */
var rowCount = [];
for (var i = 0; i < totalRows; i++) {
rowCount[i] = "";
spaceCount = 0;
for (var j = 0; j < totalCols; j++) {
if (puzzle[i][j] == "#") {
spaceCount++;
if (j == totalCols - 1) {
rowCount[i] += spaceCount + " ";
}
} else if (spaceCount > 0) {
rowCount[i] += spaceCount + " ";
spaceCount = 0;
}
}
}
The confusing parts are probably the if blocks in the middle.
if (puzzle[i][j] == "#") { // If a puzzle piece is `#` (a space?)
spaceCount++; // Increment the spaceCount by 1.
if (j == totalCols - 1) { // Only if we are on the last column, add the text
// to the row.
rowCount[i] += spaceCount + " ";
}
} else if (spaceCount > 0) { // If the current piece isn't a `#` but
// spaces have already been counted,
// add them to the row's text and reset `spaceCount`
rowCount[i] += spaceCount + " ";
spaceCount = 0;
}
From what I can tell, this code counts the number of consecutive pound signs and appends this text to each row.