I'm trying to make a container div for each image and its description at each iteration in my for loop, but JQuery is lumping all the image divs and description divs together into one container div, and that's messing up the whole layout.
I'm not sure why it's doing that, especially since I'm creating a new container div and appending to it within the for loop.
Here's the JSFiddle: https://jsfiddle.net/ZEZEME/wza7q3tn/4/
HTML
<div class=PgTwo></div>
JS
$.getJSON(url, function(data) {
arr = data.data;
for (var i = 0; i < arr.length; i++) {
var articleInfo = arr[i];
console.log(articleInfo);
var imgURL = articleInfo["listingimage"]['url'];
var title = articleInfo["title"];
var desc = articleInfo["listingdescription"];
if (imgURL != "") {
var imgWrapperDiv = document.createElement('div');
var imgDiv = document.createElement('div');
var descDiv = document.createElement('div');
imgDiv.id = 'imgDiv';
imgWrapperDiv.id = 'imgWrapperDiv';
descDiv.id = 'descDiv';
descDiv.textContent = desc;
var imgurlCSS = 'url("'+imgURL+'")';
$(imgDiv).css({'background-image': imgurlCSS, 'background-repeat': 'no-repeat', 'background-size': 'cover'});
$(imgDiv).append($('<a href="" id=link >'+ title +'</a>').css('text-decoration', 'none'));
$('#imgWrapperDiv').append(imgDiv);
$('#imgWrapperDiv').append(descDiv);
$('.PgTwo').append(imgWrapperDiv);
}
}
});
You're only using one id in the for loop. So you're creating the wrapper div, then setting its id but every time it sets it to the same id as before. In the DOM only one wrapper div is present then.
Related
This code is not creating a single div in the webpage which i linked the js below. how can i makes changes in the js or html for the code to be executed as expected
var div,
container = document.getElementById("container");
for (var i = 0; i < 5; i++) {
div = document.createElement("div");
div.onclick = function () {
alert("This is box #" + i);
};
container.appendChild(div);
}
1) To show a div you have to include some text inside divtag
2) You should use let instead of var to get the correct number when user click on div
var div,
container = document.getElementById("container");
for (let i = 0; i < 5; i++) { // change -> let instead of var
div = document.createElement("div");
div.textContent = `div${i}` // change -> add some text
div.onclick = function() {
alert("This is box #" + i);
};
container.appendChild(div);
}
<div id="container"></div>
This question already has answers here:
Append multiple items in JavaScript
(15 answers)
Closed 4 years ago.
This is my code:
var div4=document.getElementById('div4'); // get the div element
var div2=document.getElementById('div2'); // create a new div
for (var index = 0; index < array.length; index++) {
var newDiv=document.createElement("div"); //create a new div
var newDiv2=document.createElement("div") //create a new div
newDiv.innerHTML=array[index];
newDiv.draggable = true;
newDiv.id = 'record-2-'+index;
newDiv.className = 'record';
newDiv2.className = 'record';
newDiv2.id = 'record-4-'+index;
newDiv2.draggable = true;
newDiv2.innerHTML=array[index];
div4.appendChild(newDiv); // append to div
div2.appendChild(newDiv2); // append to div
newDiv.addEventListener("dragstart", handleDragStart);
newDiv2.addEventListener("dragstart", handleDragStart);
}
How I can achive same functionality without having two separate variable newDiv, newDiv2.
You could clone the div and add that by using cloneNode(), so you are adding two separate divs, not the one same one.
var div4=document.getElementById('div4'); // get the div element
var div2=document.getElementById('div2'); // create a new div
for (var index = 0; index < array.length; index++) {
var newDiv=document.createElement("div"); //create a new div
newDiv.innerHTML=array[index];
newDiv.draggable = true;
newDiv.id = 'record-2-'+index;
newDiv.className = 'record';
div4.appendChild(newDiv); // append to div
newDiv = newDiv.cloneNode(false); // clone the div
newDiv.id = 'record-4-'+index; // change its id property
div2.appendChild(newDiv); // append to div
newDiv.addEventListener("dragstart", handleDragStart);
newDiv2.addEventListener("dragstart", handleDragStart);
}
You could create a function wich return or adds the div to a passed div:
//Required..
function handleDragStart(){};
//Created and append divs
function addDivTo(div, html, id){
//appendChild() returns the input
var newDiv = div.appendChild(document.createElement("div")); //create a new div
newDiv.id = id;
newDiv.innerHTML = html;
newDiv.draggable = true;
newDiv.className = 'record';
newDiv.addEventListener("dragstart", handleDragStart)
}
//Some array used below
var array = ['123', '456', '789', 'cucubau'];
var div4 = document.getElementById('div4'); // get the div element
var div2 = document.getElementById('div2'); // create a new div
for (var index = 0; index < array.length; index++) {
addDivTo(div4, array[index], 'record4-' + index);
addDivTo(div2, array[index], 'record2-' + index)
}
<div id = 'div4'></div>
<div id = 'div2'></div>
JS doesn't display the output
for (var i = 0; i < obj.Search.length; i++){
var divTag = document.createElement("div");
divTag.id = "div"+i;
divTag.className = "list";
document.getElementById('div'+i).innerHTML+=obj.Search[i].Title+obj.Search[i].Year;
}
Image here
You missed adding the newly created element to the DOM. Example:
document.getElementById("yourDivContainer").appendChild(divTag);
Fiddle:
http://jsfiddle.net/mbpfgm49/
You need to append your div tags to some element (e.g: body), to make text appear on page
// Let's create some sample data
var obj = {
Search: []
}
var currentYear = (new Date).getFullYear();
for (var i = currentYear - 10; i <= currentYear; i++) {
obj.Search.push({
Title: 'Test',
Year: i
})
}
// Here goes your code fixed
for (var i = 0; i < obj.Search.length; i++) {
var divTag = document.createElement("div");
divTag.id = "div" + i;
divTag.className = "list";
divTag.innerHTML = obj.Search[i].Title + ' ' + obj.Search[i].Year;
document.body.appendChild(divTag);
}
Yes, you have to add the element to the DOM.
More basically, it is an anti-pattern to construct IDs for elements and use those as the primary means for referring to elements, by means of calling getElementById at every turn. I guess this approach is one of the many lingering after-effects of the jQuery epidemic.
Instead, keep references to elements directly in JS where possible, and use them directly:
for (var i = 0; i < obj.Search.length; i++){
var divTag = document.createElement("div");
divTag.className = "list";
parent.appendChild(divTag);
^^^^^^^^^^^^^^^^^^^^^^^^^^ INSERT ELEMENT
divTag.innerHTML+=obj.Search[i].Title+obj.Search[i].Year;
^^^^^^ REFER TO ELEMENT DIRECTLY
}
To be absolutely pedantically correct, what you are creating is not a "tag", it's an "element". The element is the DOM object. The "tag" is the div which characterizes the element type.
I have a js question that annoys me for the last couple of days.
i have a parallax template, where the parallax elements are generated automatically from js file.So i can add css style like transitions etc., but i would like to add some links on top of the divs, or some kind of on clik events.
What i think i have to look so far is in this fille (where the id of the divs are created):
enter //Parallax Element 2
var item = {};
item.name = "#tree21";
item.stackOrder = 1;
item.content = "image";
item.image = "images/parallax/bg2.png";
item.sizes = {w:"350",h:"350"};
item.screenPos = ["40%","-100%","300%","-115%"];
item.visibility = ["true","true","true","true"];
item.parallaxScene = true;
item.bPos = 200;
item.mouseSpeed = 15;
items.push(item);
and here (where i think the divs are generated
createScenes: function () {
//Resize Parallax Elements if responsive
if (responsive) {
var screenProp = this.maxWidth / 1920;
} else {
var screenProp = 1;
}
for (var i = 0; i < items.length; i++) {
if (jQuery(items[i].name).length == 0) {
jQuery("#parallax-container").append("<div id='" + items[i].name.substring(1, (items[i].name.length)) + "' class='parallaxItem'></div>");
}
Thank you!
Store a reference to your new div:
var div = jQuery("<div id='"
+ items[i].name.substring(1, (items[i].name.length))
+ "' class='parallaxItem'></div>")
.appendTo(jQuery("#parallax-container"));
jQuery(div).append('...');
I'm confused on how to change text content of div with the DOM. When event is triggered, I see that the new text replace the old but it is in a new div. I want to keep it in "transcriptText" to keep all attributes.`How can I do that?
This is my old div with text inside:
var transcriptText = document.getElementById("transcriptText");
these are my new text SPAN elements
var newTranscript = document.createElement("div");
This is how I handle the event
function EventHandler() {
transcriptText.parentNode.replaceChild(newTranscript, transcriptText);
}
Here is the JSFiddle on how it currently works:
http://jsfiddle.net/b94DG/
What you're doing now is creating a new div, newTranscript, which you create by appending a bunch of spans based on the old text. Then in your event handler you replace the old one with the new one. Instead of that, you could still copy the text from the old one, but then clear it and append the children on the old div, replacing line 36 with:
transcriptText.appendChild(newSpan);
To clear the old element, it might work to just set innerHTML to "", or if necessary you could remove all the children with removeChild as described at https://developer.mozilla.org/en-US/docs/Web/API/Node.removeChild
EDIT:
I modified your fiddle to reflect this:
http://jsfiddle.net/b94DG/1/
You can change the innerHTML of transcriptText instead of creating a new div.
var transcriptText = document.getElementById("transcriptText");
var divideTranscript = document.getElementById("divideTranscript");
divideTranscript.onclick = function() {
var sArr = transcriptText.innerHTML.split(" ");
var newInnerHTML = "";
for (var i = 0; i < sArr.length; i++) {
var item = sArr[i];
var newText = "<span class='highlight' id='word" + i + "'>" + item + " </span>";
newInnerHTML += newText;
}
transcriptText.innerHTML = newInnerHTML;
var mouseOverFunction = function () {
this.style.backgroundColor = 'yellow';
};
var mouseOutFunction = function () {
this.style.backgroundColor = '';
};
var highlight = document.getElementsByClassName("highlight");
for (i = 0; i < highlight.length; i++) {
highlight[i].onmouseover = mouseOverFunction;
highlight[i].onmouseout = mouseOutFunction;
}
};
Here's the fiddle: http://jsfiddle.net/khnGN/