Using InnerHTML on 144 different cells - javascript

I am creating a tile based game using tables. In each td cell,
<td>
<div id="image" style="display:none; display: fixed; right: 5; top:2;"><img src="http://thumb7.shutterstock.com/display_pic_with_logo/339217/339217,1272881114,1/stock-vector-hand-drawing-of-typical-house-along-the-canal-near-bangkok-in-thailand-52242874.jpgAttap"/></div>
<input id ="attap" type="submit" value="Show Div" onclick="showDiv(); if(submitted)this.disabled = true" />
<div id="welcomeDiv" style="display:none;"> <input type="submit" name="answer" value="Show Div" onclick="showDiv3(); if(submitted)this.disabled = true" /></div>
<div id="welcomeDiv3" style="display:none;"> <input type="submit" name="answer" value="Show Div" onclick="showDiv4(); if(submitted)this.disabled = true"" /></div>
<div id= "welcomeDiv4" style="display:none;"><input type="submit" name="answer" value="Show Div" onclick="showDiv5(); if(submitted)this.disabled = true"" /> </div>
</td>
Javascipt:
function showDiv() {
document.getElementById('welcomeDiv').style.display = "block";
document.getElementById('image').style.display = "block";
submitted = true;
populationred +=20;
document.getElementById('population').innerHTML = populationred;
}
function showDiv3() {
document.getElementById('welcomeDiv3').style.display = "block";
document.getElementById("image").innerHTML = "'<img src='http://www.sgshophouses.com/images/Shophouses1.jpg'>'"
submitted = true;
populationred +=50;
document.getElementById('population').innerHTML = populationred;
}
function showDiv4() {
document.getElementById('welcomeDiv4').style.display = "block";
document.getElementById('image').innerHTML = "'<img src='http://singaporepropertylaunch.com.sg/wp-content/uploads/2015/04/HDB-resale-prices-fall-1.0.gif'>'"
submitted = true;
populationred +=100;
document.getElementById('population').innerHTML = populationred;
}
function showDiv5() {
document.getElementById('image').innerHTML = "'<img src='www.realestatechannel.com/assets_c/2010/06/Austonian-Condo-Tower-thumb- 120x238.jpg'>'"
submitted = true;
populationred +=200;
document.getElementById('population').innerHTML = populationred;
}
I need to repeat this for 144 cells. However, the problem is that when 1 button is clicked, the image will show up only at the first cell, hence the tedious way of solving this issue is to rename all the divs differently for every cell. Is there any more efficient ways?
You can refer here: www2.hci.edu.sg/t0104448b/cells.html for a "fiddle".

Shilly's comment had the right idea. I'm not entirely sure what your goal is but this is what I did, that looks reasonably what you're after. It should get you started.
There's only one click handler, on the <table> itself. It's effectively delegating the click. This saves memory because you're not creating a copy/closure for every cell. It costs some performance due to the delegating nature but for click handlers, it's generally okay. For mouseover handlers, that's another subject.
Using a <template> tag effectively gives you a DocumentFragment to work with and markup as HTML, instead of doing it in JavaScript (which can be tedious).
We clone that document fragment 144 times, injecting the proper description ('ShopHouse', 'HDB Flat', 'Condo', etc.) into each stamp of the template. Each clone is appended to a document fragment. Once our document fragment is done being modified, we inject it into the DOM via board.appendChild(frag);.
var board = document.getElementById('board');
var cellTmpl = document.getElementById('template-cell');
var cellTmplContent = cellTmpl.content;
var frag = document.createDocumentFragment(); // for performance
var submitted = false; // not sure what you intend to use this for
var descriptions = [ 'ShopHouse', 'HDB Flat', 'Condo' ]; // ... etc.
var cells = [];
for (var r = 0; r < 12; r++) {
var row = [];
cells.push(row);
var tr = document.createElement('tr');
frag.appendChild(tr);
for (var c = 0; c < 12; c++) {
var clone = document.importNode(cellTmplContent, true);
var index = r * 12 + c;
var description = index < descriptions.length ? descriptions[index] : 'Unknown place';
clone.querySelector('p.description').innerText = description;
tr.appendChild(clone);
row.push(clone);
}
}
board.appendChild(frag);
board.addEventListener('click', function(e) {
var button = e.target;
var td = button.parentElement;
var img = td.querySelector('img');
var p = td.querySelector('p.description');
button.disabled = true;
img.style.display = 'block';
p.style.display = 'block';
submitted = true;
});
// could do something with `cells` variable if you like. It's a two dimensional array of <td> elements
td {
background: #ccc;
border: 1px solid #000;
}
td > img {
display: none;
zoom: 0.2;
}
p.description {
display: none;
}
<table id="board">
</table>
<template id="template-cell">
<td>
<img src="http://thumb7.shutterstock.com/display_pic_with_logo/339217/339217,1272881114,1/stock-vector-hand-drawing-of-typical-house-along-the-canal-near-bangkok-in-thailand-52242874.jpgAttap"/>
<button>Show</button>
<p class="description"></p>
</td>
</template>

Related

Generate and Render html from a set of inputs

I have a word matching exercise that takes a set of inputs.
The program reads the html from the input boxes.
Then the html is displayed in a textarea element.
When the user clicks "render html" the key words and descriptions are displayed. The html displayed by the program are the values are taken from value of the textarea element.
The input elements for the html are
<div id="inputBoxes" class="inputBoxes">
<title>Input:</title>
<div class="row">
Title: <input id= "title_input" type="text">
</div>
<div class="row">
Key Term 1: <input id="el1" type="text" value="">
</div>
<div class="row">
Description 1: <input id="dl1" type="text" value="">
</div>
<div class="row">
Key Term 2: <input id="el2" type="text" value="">
</div>
<div class="row">
Description 2: <input id="dl2" type="text" value="">
</div>
</div>
I have 3 global variables to keep track of the numberOfInputs, htmlGenerated, htmlRendered. The reasoning behind this is to check if
New inputs have been added. If new inputs have been added then when the user clicks generate html those new inputs should be added. When the user clicks render html those new inputs should be added.
Check if html has been generated. If the html was generated then it should be removed before generating new html.
Check if html has been rendered. If the html was rendered then it should be removed before rendering new html.
The global variables used are
// initially html is not generated.
var htmlGenerated = false;
// number of inputs start out as 2.
var numberOfInputs = 2;
// initially no addtional inputs have been added.
var addMore = false;
// initially html is not rendered
var htmlRendered = false;
I've created three methods for accomplishing this goal.
generate_html()
add_more()
render_html()
There is a reset function that should remove the controls, the textarea, and the rendered html.
function generate_html() {
//have we added more?
if(addMore && htmlGenerated){
// then delete the old textarea.
textarea = document.getElementById("generated_html_textarea");
textarea.remove();
// delete the controls.
controls = document.getElementById("program1");
controls.remove();
}
//has the html already been generated?
if(!htmlGenerated){
const e_inputs = document.querySelectorAll("[id^='el']");
const d_inputs = document.querySelectorAll("[id^='dl']");
const title = document.getElementById('title_input').value;
let elArray = [];
let dlArray = [];
e_inputs.forEach( i => { if(i.value) elArray.push(i.value) });
d_inputs.forEach( i => { if(i.value) dlArray.push(i.value) });
let text = title + "\n";
for (let i = numberOfInputs; i < elArray.length; i++) {
text += `${elArray[i]}:${dlArray[i]}\n`;
}
//fetch the results box
results = document.getElementById("results");
//create textarea
textarea = document.createElement("textarea");
textarea.setAttribute("id","generated_html_textarea");
// initialize blank html
html = '';
//create key inputs
for (let i = numberOfInputs; i < elArray.length+numberOfInputs; i++){
html += '<div id="s';
id = (1+i-numberOfInputs);
html += id;
html +='\" class=\"draggyBox-small\">';
html += elArray[i-numberOfInputs];
html +='</div>\n';
}
//create description inputs
html += '<table id=\"tablestyle\">'
for (let i = numberOfInputs; i < dlArray.length+numberOfInputs; i++){
html += '<td id="row';
id = (1+i-numberOfInputs);
html += id;
html +='">\n';
html += '\t\t<div id=\"t';
html +=i-numberOfInputs;
html +='" class=\"ltarget\"></div>\n \t</td >\n \t<td id=\"d2\">'
html +=dlArray[i-numberOfInputs];
html +='</td >\n </tr>\n';
}
html += '</table>';
// html generation is done.
htmlGenerated = true;
textarea.value = html;
results.appendChild(textarea);
// Generate reset, show answer, , and render html buttons
controls = document.createElement("div");
controls.setAttribute("id","program1");
controls.setAttribute("style","border: 1px solid #EB0D1B; width: 360px; font-family: courier; font-size: 100.5%; margin: 0px auto; border: 1px; text-align: center; margin-top: 5px;");
controls.innerHTML += '<span style="padding: 3px"> <button id ="one" class="button" type="button" onClick="one()">Show Answer</button> <button id = "resetButton" class="button" type="button" onClick="reset()">Reset</button><button id = "renderHTMLButton" class="button" type="button" onClick="render_html()">Render html</button> <span id = "audio" style=""> <img id="bg" src="audioOff.png" height="30" width="30" style="margin-bottom:-10px; padding-bottom:-20px;"/> </span> </span>';
results.appendChild(controls);
}
}
function add_more() {
// we've added more inputs.
addMore = true;
// set html generated to false, because new inputs have been added.
htmlGenerated = false;
// increment the number of inputs.
numberOfInputs++;
//fetch the input boxes.
inputs = document.getElementById("inputBoxes");
//create a new row for a key term.
row = document.createElement("div");
row.setAttribute("class","row");
// set the key term text.
row.innerHTML = "Key Term ";
row.innerHTML +=numberOfInputs;
row.innerHTML +=" :";
// create the input for the key.
key = document.createElement("input");
key.setAttribute("id","el"+numberOfInputs);
//add the key to the row.
row.appendChild(key);
//create a row for the new description.
row2 = document.createElement("div");
row2.setAttribute("class","row");
// set the description text.
row2.innerHTML = "Description "
row2.innerHTML+=numberOfInputs;
row2.innerHTML+=" :";
// create the description input
description = document.createElement("input");
description.setAttribute("id","dl"+numberOfInputs);
// add the description to the row.
row2.appendChild(description);
// add the rows for the key and the description to the inputBoxes.
inputs.appendChild(row);
inputs.appendChild(row2);
}
function render_html(){
// was html rendered?
if(!htmlRendered){
textarea = document.getElementById("generated_html_textarea");
generated_html = textarea.value;
console.log(generated_html);
maincontentstyle = document.getElementById("maincontentstyle");
rendered_html = document.createElement("div");
rendered_html.setAttribute("id","rendered_html");
rendered_html.setAttribute("style","border: 1px solid #EB0D1B; width: 360px; font-family: courier; font-size: 100.5%; margin: 0px auto; border: 1px; text-align: center; margin-top: 5px;");
rendered_html.innerHTML += generated_html;
maincontentstyle.appendChild(rendered_html);
htmlRendered = true;
}
}
function reset() {
// reset the htmGenerated to false.
htmlGenerated = false;
htmlRendered = false;
numberOfInputs = 2;
var someVarName = true;
sessionStorage.setItem("someVarKey1", someVarName);
window.location.reload();
}
The issue that I'm facing is
When the user clicks generate html with the initial inputs set to valid values the generated html is created properly. When the user clicks add more and then clicks generated html a second div with a second textarea and second set of controls are created. This should not happen. The original textarea and controls should be replaced.
Any help with this would be greatly appreciated.
In add_more(), comment out the htmlGenerated = false; line (since clicking the "add more" button doesn't remove the generated html) and in generate_html() add htmlGenerated = false; after controls.remove();.
// initially html is not generated.
var htmlGenerated = false;
// number of inputs start out as 2.
var numberOfInputs = 2;
// initially no addtional inputs have been added.
var addMore = false;
// initially html is not rendered
var htmlRendered = false;
function generate_html() {
//have we added more?
if (addMore && htmlGenerated) {
// then delete the old textarea.
textarea = document.getElementById("generated_html_textarea");
textarea.remove();
// delete the controls.
controls = document.getElementById("program1");
controls.remove();
htmlGenerated = false;
}
//has the html already been generated?
if (!htmlGenerated) {
const e_inputs = document.querySelectorAll("[id^='el']");
const d_inputs = document.querySelectorAll("[id^='dl']");
const title = document.getElementById('title_input').value;
let elArray = [];
let dlArray = [];
e_inputs.forEach(i => {
if (i.value) elArray.push(i.value)
});
d_inputs.forEach(i => {
if (i.value) dlArray.push(i.value)
});
let text = title + "\n";
for (let i = numberOfInputs; i < elArray.length; i++) {
text += `${elArray[i]}:${dlArray[i]}\n`;
}
//fetch the results box
results = document.getElementById("results");
//create textarea
textarea = document.createElement("textarea");
textarea.setAttribute("id", "generated_html_textarea");
// initialize blank html
html = '';
//create key inputs
for (let i = numberOfInputs; i < elArray.length + numberOfInputs; i++) {
html += '<div id="s';
id = (1 + i - numberOfInputs);
html += id;
html += '\" class=\"draggyBox-small\">';
html += elArray[i - numberOfInputs];
html += '</div>\n';
}
//create description inputs
html += '<table id=\"tablestyle\">'
for (let i = numberOfInputs; i < dlArray.length + numberOfInputs; i++) {
html += '<td id="row';
id = (1 + i - numberOfInputs);
html += id;
html += '">\n';
html += '\t\t<div id=\"t';
html += i - numberOfInputs;
html += '" class=\"ltarget\"></div>\n \t</td >\n \t<td id=\"d2\">'
html += dlArray[i - numberOfInputs];
html += '</td >\n </tr>\n';
}
html += '</table>';
// html generation is done.
htmlGenerated = true;
textarea.value = html;
results.appendChild(textarea);
// Generate reset, show answer, , and render html buttons
controls = document.createElement("div");
controls.setAttribute("id", "program1");
controls.setAttribute("style", "border: 1px solid #EB0D1B; width: 360px; font-family: courier; font-size: 100.5%; margin: 0px auto; border: 1px; text-align: center; margin-top: 5px;");
controls.innerHTML += '<span style="padding: 3px"> <button id ="one" class="button" type="button" onClick="one()">Show Answer</button> <button id = "resetButton" class="button" type="button" onClick="reset()">Reset</button><button id = "renderHTMLButton" class="button" type="button" onClick="render_html()">Render html</button> <span id = "audio" style=""> <img id="bg" src="audioOff.png" height="30" width="30" style="margin-bottom:-10px; padding-bottom:-20px;"/> </span> </span>';
results.appendChild(controls);
}
}
function add_more() {
// we've added more inputs.
addMore = true;
// set html generated to false, because new inputs have been added.
// htmlGenerated = false;
// increment the number of inputs.
numberOfInputs++;
//fetch the input boxes.
inputs = document.getElementById("inputBoxes");
//create a new row for a key term.
row = document.createElement("div");
row.setAttribute("class", "row");
// set the key term text.
row.innerHTML = "Key Term ";
row.innerHTML += numberOfInputs;
row.innerHTML += " :";
// create the input for the key.
key = document.createElement("input");
key.setAttribute("id", "el" + numberOfInputs);
//add the key to the row.
row.appendChild(key);
//create a row for the new description.
row2 = document.createElement("div");
row2.setAttribute("class", "row");
// set the description text.
row2.innerHTML = "Description "
row2.innerHTML += numberOfInputs;
row2.innerHTML += " :";
// create the description input
description = document.createElement("input");
description.setAttribute("id", "dl" + numberOfInputs);
// add the description to the row.
row2.appendChild(description);
// add the rows for the key and the description to the inputBoxes.
inputs.appendChild(row);
inputs.appendChild(row2);
}
function render_html() {
// was html rendered?
if (!htmlRendered) {
textarea = document.getElementById("generated_html_textarea");
generated_html = textarea.value;
console.log(generated_html);
maincontentstyle = document.getElementById("maincontentstyle");
rendered_html = document.createElement("div");
rendered_html.setAttribute("id", "rendered_html");
rendered_html.setAttribute("style", "border: 1px solid #EB0D1B; width: 360px; font-family: courier; font-size: 100.5%; margin: 0px auto; border: 1px; text-align: center; margin-top: 5px;");
rendered_html.innerHTML += generated_html;
maincontentstyle.appendChild(rendered_html);
htmlRendered = true;
}
}
function reset() {
// reset the htmGenerated to false.
htmlGenerated = false;
htmlRendered = false;
numberOfInputs = 2;
var someVarName = true;
sessionStorage.setItem("someVarKey1", someVarName);
window.location.reload();
}
<div id="inputBoxes" class="inputBoxes">
<title>Input:</title>
<div class="row">
Title: <input id= "title_input" type="text" value="t">
</div>
<div class="row">
Key Term 1: <input id="el1" type="text" value="k1">
</div>
<div class="row">
Description 1: <input id="dl1" type="text" value="d1">
</div>
<div class="row">
Key Term 2: <input id="el2" type="text" value="k2">
</div>
<div class="row">
Description 2: <input id="dl2" type="text" value="d2">
</div>
</div>
<div>
<button onClick="generate_html()">Generate</button>
<button onClick="add_more()">More</button>
</div>
<div id="results"></div>
<div id="maincontentstyle"></div>

Having trouble with displaying an image through an array

I am practicing with JavaScript Array function. What I want to achieve is to show google embedded images inside the display section when the user clicks "Show my grocery list" button after entering "banana", else the texts will be shown instead.
These are my codes.
var grocery = document.getElementById("grocery");
let showItems = document.getElementById("showItems");
const display = document.getElementById("display");
var groceryList = [];
grocery.addEventListener("keyup",function(ev){
if(ev.keyCode == 13){
groceryList.push(grocery.value);
console.log("array",groceryList);
}
});
showItems.addEventListener("click",function(){
for (var i = 0; i < groceryList.length;i++){
if(groceryList[i] == "banana"){
display.src = "https://i5.walmartimages.ca/images/Enlarge/271/747/6000191271747.jpg";
} else {
display.innerHTML += groceryList[i] + "<br/>";
}
}
});
#display {
width:100px;
height:100px;
}
<div id="controls">
<input type="text" placeholder="grocery items" id="grocery"/>
<button id="showItems">Show My Grocery List</button>
</div>
<div id="display"></div>
It is currently not showing anything. I have a feeling that I have written a wrong syntax inside the loop function? I would appreciate a solution and tips. Thank you.
You've to remove the keyCode=13 condition first and then need to create an img element with src of image based on condition (groceryList[i] == "banana") to display the image inside the <div> element, For example:
var grocery = document.getElementById("grocery");
let showItems = document.getElementById("showItems");
const display = document.getElementById("display");
var groceryList = [];
grocery.addEventListener("keyup", function(ev) {
//if(ev.keyCode == 13){
groceryList.push(grocery.value);
//console.log("array",groceryList);
//}
});
showItems.addEventListener("click", function() {
for (var i = 0; i < groceryList.length; i++) {
if (groceryList[i] == "banana") {
var source = "https://i5.walmartimages.ca/images/Enlarge/271/747/6000191271747.jpg";
var img = document.createElement("IMG"); //create img element
img.src = source; //set img src
display.appendChild(img); // display image inside <div>
} else {
display.innerHTML += groceryList[i] + "<br/>";
}
}
});
<div id="controls">
<input type="text" placeholder="grocery items" id="grocery" />
<button id="showItems">Show My Grocery List</button>
</div>
<div id="display"></div>

How to show nearest div id for a given input number?

Let's say I have the following input field:
<input id="inputField" type="number" value="">
and some divs such as:
<div id="1000"></div>
<div id="1200"></div>
<div id="1500"></div>
<div id="1900"></div>
...
When the user enters a number in the input field, I want my code to go to the nearest div id to that number.
e.g: If user enters 1300 then show div with id = "1200".
What's the most efficient way to implement that in javascript considering there will be a large number of divs?
Right now I'm doing:
<script>
function myFunction()
{
var x = document.getElementById("inputField").value;
if(x >= 1750 && x <= 1900)
{
window.location.hash = '#1800';
}
}
</script>
One way is to wrap all your divs with number ids in another div if you can (and give it some id, say 'numbers'); this allows you to find all the divs in your javascript file.
Javascript:
// Get all the divs with numbers, if they are children of div, id="numbers"
let children = document.getElementById('numbers').children;
let array = [];
for (i = 0; i < children.length; i++) {
// Append the integer of the id of every child to an array
array.push(parseInt(children[i].id));
}
// However you are getting your input number goes here
let number = 1300 // Replace
currentNumber = array[0]
for (const value of array){
if (Math.abs(number - value) < Math.abs(number - currentNumber)){
currentNumber = value;
}
}
// You say you want your code to go to the nearest div,
// I don't know what you mean by go to, but here is the div of the closest number
let target = document.getElementById(currentNumber.toString());
Let me know if there's more I can add to help.
Demo
function closestNum() {
let children = document.getElementById('numbers').children;
let array = [];
for (i = 0; i < children.length; i++) {
array.push(parseInt(children[i].id));
}
let number = document.getElementById('inputnum').value;
currentNumber = array[0]
for (const value of array) {
if (Math.abs(number - value) < Math.abs(number - currentNumber)) {
currentNumber = value;
}
}
let target = document.getElementById(currentNumber.toString());
document.getElementById('target').innerHTML = target.innerHTML;
}
<div id="numbers">
<div id="1000">1000</div>
<div id="2000">2000</div>
<div id="3000">3000</div>
<div id="4000">4000</div>
<div id="5000">5000</div>
</div>
<br />
<input type="text" id="inputnum" placeholder="Input Number" onchange="closestNum()" />
<br />
<br /> Target:
<div id="target"></div>
With some optimization this shall be ok-
var element;
document.addEventListener("change",
function(evt){
if(element && element.classList){
element.classList.remove("selected", false);
element.classList.add("unselected", true);
}
var listOfDivs =
document.querySelectorAll(".unselected");
var val = evt.target.value;
var leastAbs=listOfDivs[0].id;
for(let anIndex=0, len=listOfDivs.length;anIndex<len;anIndex++){
if(Math.abs(listOfDivs[anIndex].id-val)<leastAbs){
leastAbs = Math.abs(listOfDivs[anIndex].id-val);
element = listOfDivs[anIndex];
}
}
element.classList.remove("unselected");
element.classList.add("selected");
});
.selected{
background-color:red;
}
.unselected{
background-color:yellow;
}
.unselected, .selected{
width:100%;
height:50px;
}
<input id="inputField" type="number" value="">
<div id="1000" class='unselected'>1</div>
<div id="1200" class='unselected'>2</div>
<div id="1500" class='unselected'>3</div>
<div id="1900" class='unselected'>4</div>
This may work for you. Loops through each div and compared it to your inputted ID. Tracks closest one, hides all divs, then displays the closest.
document.getElementById("inputField").addEventListener("change", function(){
var divs = document.getElementsByTagName("div");
var closestDiv = -1;
var inputId = document.getElementById("inputField").value;
for(var i=0; i<divs.length; i++)
{
if(Math.abs(inputId - closestDiv) > Math.abs(inputId - divs[i].id) || closestDiv == -1)
{
closestDiv = divs[i].id;
for (var x = 0; x < divs.length; x++) {
divs[x].style.display = 'none';
}
divs[i].style.display = "block";
}
}
});
See it Live: jsfiddle.net

What's wrong with this code to move css elements with javascript?

I am trying to move an element with javascript. I searched for a while and I think that this code should do the trick... but it does not, and I get no errors in the Console... anybody can help?
<html><body>
<script>
function move1(){
var cusid_ele = document.getElementsByClassName('zzz');
for (var i = 0; i < cusid_ele.length; ++i) {
var item = cusid_ele[i];
var x=item.style.top;
x+=10;
item.style.top=x;
}
}
function move2(){
var cusid_ele = document.getElementsByClassName('zzz');
for (var i = 0; i < cusid_ele.length; ++i) {
var item = cusid_ele[i];
var x=item.style["top"];
x+=10;
item.style["top"]=x;
}
}
function move3(){
var cusid_ele = document.getElementsByClassName('zzz');
for (var i = 0; i < cusid_ele.length; ++i) {
var item = cusid_ele[i];
var x=item.style["top"];
x+=10;
item.style["top"]=x+'px';
}
}
</script>
<input type=button onclick="move1();" value="Move (1st way, with .top=x)!">
<input type=button onclick="move2();" value="Move (2nd way, with [top]=x)!">
<input type=button onclick="move3();" value="Move (3rd way, with [top]=xpx)!">
<h3 class=zzz >Move me! (no inline style)</h3>
<h3 class=zzz style="top: 50px;">Move me! (with inline style)</h3>
</body></html>
By the way, I tried both FF and Chrome...
-- Accepted solution, I write it here so one can have a working example (thank you Adeneo!):
<script>
function move1(){
var cusid_ele = document.getElementsByClassName('zzz');
for (var i = 0; i < cusid_ele.length; ++i) {
var item = cusid_ele[i];
var x = parseInt( item.style.top, 10 );
x+=10;
item.style.top=x+'px';
}
}
</script>
<input type=button onclick="move1();" value="Move!">
<h3 class=zzz >I cant move! (no css positioning)</h3>
<h3 class=zzz style="position: relative; top: 50px;">I can move! (with css positioning)</h3>
</body></html>
This
var x=item.style["top"];
returns the string 300px etc, so
x += 10;
ends up being
300px10
so replace
var x=item.style.top;
with
var x = parseInt( item.style.top, 10 );
the same goes for setting styles
element.style.top = x + 'px';
You'll have to use a string with units, and to make the CSS actually do something, the elements must be positioned
FIDDLE

Dynamic Div ID and Creating Elements Inside it

I am creating a dynamic Div where i can import values from the showModalDialog when it is closed. So after closing the modal, i get couple of values.
What i am trying to do here is:
I have couple of dynamic div's and against each div, i have a link to open a window.
After selection of the files they are return back to the parent window as comma separated.
I want to insert those values inside the div to which that popup was opened. but in this scenario i am facing the trouble. the Divid's are generated dynamically
Here is the Complete Code for Javascript + Jquery Based, I am getting the following error.
TypeError: theDiv.appendChild is not a function
[Break On This Error]
theDiv.appendChild(newNode);
<script type="text/javascript" src="JS/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
function eliminateDuplicates(arr,divID)
{
var i,
len=arr.length,
out=[],
obj={};
for (i=0;i<len;i++)
{
obj[arr[i]]=0;
}
for (i in obj)
{
out.push(i);
}
return out;
}
function GetElementsStartingWith(tagName, subString) {
var elements = document.getElementsByTagName(tagName);
var result = [];
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
if (element.id && element.id.substr(0, subString.length) == subString) {
result.push(element);
}
}
return result;
}
Test= function(str,divID)
{
var arrID = new Array();
arrID = str.split(',');
arrID = eliminateDuplicates(arrID);
var theDiv = $("#projectsList"+divID).attr('id'); //document.getElementById('projectsList');
alert(theDiv);
var cmp= $("#projectIDS"+divID).val(); //document.getElementById("projectIDS").value;
var cnp = $("#countProj"+divID);//document.getElementById("countProj")
var cproj;
if(cnp.val().length == 0)
cproj=0;
else
cproj=parseInt(cnp.val());
for (var j=0; j<arrID.length; j++)
{
if (parseInt(cproj) + 1 > 50)
{
alert("You cannot add more than 50 Project id's ");
return;
}
if( cmp!="" && cmp.indexOf(arrID[j])!=-1)
continue;
var newNode = document.createElement('div');
newNode.style.cssText = "background:#CCCCCC;border:1px solid #666666;width:100px;word-wrap:break-word;margin:3px;float:left;color:black;text-decoration:none!important;height:auto;vertical-align:middle;padding-top:2px;";
newNode.title = arrID[j]+" ";
newNode.innerHTML = '<input type=hidden name=Proj_' + j + ' ' + 'value=' + arrID[j] + '>' + arrID[j] + ' <b>X</b>';
theDiv.appendChild(newNode);
if(cmp.length == 0)
{
//document.getElementById("projectIDS").value=arrID[j]
$("#projectIDS"+divID).val(arrID[j]);
}
else
{
//document.getElementById("projectIDS").value = document.getElementById("projectIDS").value+","+arrID[j];
$("#projectIDS"+divID).val($("#projectIDS"+divID).val()+","+arrID[j]);
}
cproj = parseInt(cproj)+1;
//document.getElementById("countProj").value =cproj;
cnp.value(cproj);
}
}
removetext = function(par)
{
var strremove=par.text();
var strexist = document.getElementById("projectIDS").value;
strremove = strremove.replace(" X","");
tempRemove(strexist, strremove);
par.remove();
var cproj;
if(document.getElementById("countProj").value.length == 0)
cproj=0;
else
{cproj=parseInt(document.getElementById('countProj').value);
cproj=parseInt(cproj)-1;}
document.getElementById("countProj").value =cproj;
}
function tempRemove(strexist,strremove)
{
var b = strexist.indexOf(strremove);
var after = strexist.indexOf(",",b);
var newstrexist;
var before = strexist.lastIndexOf(",",b);
if(after!=-1)
{newstrexist=strexist.replace(strremove+',',"");}
else if(before!=-1)
{newstrexist=strexist.replace(','+strremove,"");}
else
{newstrexist= strexist.replace(strremove,"");}
document.getElementById("projectIDS").value=newstrexist;
//remove current friend
}
function openWindow(divID)
{
var lookUpAlys=window.showModalDialog("files.cfm?d=" + Math.random() + '&fileID=' + divID,window,"center=yes;dialogWidth:895px:dialogHeight:785px;status:no");
if(lookUpAlys.forename!=undefined)
{
var temp = lookUpAlys.forename;
Test(temp,divID);
}
}
</script>
</head>
<body>
<table width="100%" border="0" cellspacing="2" cellpadding="1">
<tr>
<td>Choose</td>
<td>Files</td>
<td>Action</td>
</tr>
<cfloop from="1" to="5" index="i">
<cfoutput>
<tr>
<td><input type="checkbox" name="getFile" id="getFile" value="#i#" /></td>
<td><div id="projectsList#i#" style="width:500px;height:60px;overflow-y:scroll;border:1px solid gray;"></div><input type="text" name="projectIDS#i#" id="projectIDS#i#" data-id="#i#" value="" /><input type="text" data-id="#i#" name="countProj#i#" id="countProj#i#" value="" /></td>
<td>Files</td>
</tr>
</cfoutput>
</cfloop>
</table>
</body>
</html>
so my apologies if i had entered the code incorrectly. Basically trying do it Classic Javascript Way
This does not do what I think you think it does:
var theDiv = $("#projectsList"+divID).attr('id'); //document.getElementById('projectsList');
You should do
var theDiv = $("#projectsList"+divID)[0];
to get the DOM element.
Or, for this scenario, just do
var theDiv = document.getElementById("projectsList" + divID);
Also, I'm not sure why you are mixing raw DOM operations and jQuery wrapped operations everywhere. Just stick to one of them, and be consistent.
var container = $('.itemsList');
var divSubmit = $(document.createElement('div'));
//assigning id to div
$(divSubmit).attr('id','itemTemplate');
$(divSubmit).css({"font-family":"Gotham, Helvetica Neue, Helvetica, Arial, sans-serif","position":"relative","height": "70px","clear" : "both","background-color":"#FFF","border-bottom": "0.09em solid #EBEBEB"});
//adding class to main container
$(divSubmit).addClass('itemTemplate');
//adding Child's name label and assigning id to it.
var Name = '<label class="lblName" id="lblName" for="Name">'+getName()+'</label>';
$(divSubmit).append(Name);
$(divSubmit).append(container);
Here's a sample code. first of all there is sample container called itemslist
that will contain the generated div.
divSubmit will be gernerate dynamically and append to container.
To find some div for click event. Lets say we want to get child name.
alert($($(this).find("label.lblName")).val());

Categories

Resources