Add html code to a dynamically generated div - javascript

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('...');

Related

Javascript filled unsorted list auto scroll

I'm struggling to make this idea of mine work..
The idea is to auto-scroll the dynamically filled unsorted list.
This is how I've build the Unsorted List with List Items in JavaScript
$.getJSON(sportlink_url + 'programma?gebruiklokaleteamgegevens=NEE&aantaldagen=' + programma_dagen + '&eigenwedstrijden=JA&thuis=JA&uit=JA&' + sportlink_clientID, function (uitslag) {
for (let i = 0; i < Object.keys(uitslag).length; i++) {
//for (let i = 0; i < 1; i++) {
var aanvangstijd = uitslag[i].aanvangstijd;
var thuisteam = uitslag[i].thuisteam;
var uitteam = uitslag[i].uitteam;
var accommodatie = uitslag[i].accommodatie;
var competitiesoort = uitslag[i].competitiesoort;
var datumNumber = uitslag[i].datum.substring(0,2);
var datumMonth = uitslag[i].datum.slice(-4);
var datumMonthClean = datumMonth.substring(0,3);
//Fetch the DIV
var el = document.getElementById("match_program");
//Create new list item
var node = document.createElement("li");
node.setAttribute('role', 'presentation');
//Create ticketDiv
var ticketDiv = document.createElement("div");
ticketDiv.setAttribute('class', 'tg-ticket');
//Create timeBox
var timeBox = document.createElement("time");
timeBox.setAttribute('class', 'tg-matchdate');
timeBox.innerHTML = (datumNumber + " <span>" + datumMonthClean + "</span>");
//Create matchdetail
var matchDetail = document.createElement("div");
matchDetail.setAttribute('class', 'tg-matchdetail');
matchDetail.innerHTML = ("<h4>" + thuisteam + "<span> - </span>" + uitteam + "   |   " + aanvangstijd + ", " + accommodatie);
//Create themeTag
var themeTag = document.createElement("span");
themeTag.setAttribute('class', 'tg-theme-tag');
themeTag.innerHTML = (competitiesoort);
//Build the hole thing
ticketDiv.appendChild(timeBox);
matchDetail.appendChild(themeTag);
ticketDiv.appendChild(matchDetail)
node.appendChild(ticketDiv);
el.appendChild(node);
This is the Unsorted List in HTML
<ul id="match_program" class="tg-tickets tg-tabnav" role="tablist" data-autoscroll="">
</ul>
This is the function i'm currently using for auto-scroll, but it has .ulContent').height() > $('.ulContainer').height() and because my ulContent doesn't have a prefix height in CSS it's not going to work..
And I can't put a height prefix in CSS for the ulContent cause I don't know on forehand if it's going to be 500px of 800px, the unsorted list is being filled from a JSON string.
$(document).ready(function() {
if($('.ulContent').height() > $('.ulContainer').height()) {
setInterval(function () {
start();
}, 3000);
}
});
function animateContent(direction) {
var animationOffset = $('.ulContainer').height() - $('.ulContent').height();
if(direction == 'up') {
animationOffset = 0;
}
}
The animatie function is being called at the bottom of the HTML file just before the closing tags of the body
I manged to figure it out;
var amountGames = Object.keys(uitslag).length
var calulContent = amountGames * 116 + 500;
var setulContent = calulContent + "px";
document.getElementById('ulContent').style.height= setulContent;
That way the ulContent is always filled and the container uses a fixed number of 500px;

Increase the number of a limited number in a variable on scroll

I was able to list the movies from JSON file but I want to increase total number of the limited variable so when I scroll down I add 10 more movies
Here's my code
(function () {
$.getJSON("m.json", function (movie) {
var limitMovies = [];
var totalMovies = 10;
for (var i = 0; i < totalMovies; i++) {
limitMovies.push(movie[i]);
}
var movies = document.getElementById('movies');
for ( i = 0; i < limitMovies.length; i++ ) {
var addMovies = '<a id="' + i + '" class="Movie" target="_blank" href="'+ limitMovies[i].url + '/"><img src="'
+ limitMovies[i].Poster + '"/></a>';
movies.innerHTML += addMovies;
}
i = 20;
$(window).scroll(function(){
});
});
}());
I have refactored few bits of your code, and the change I have done is load all movies from file, but append them to container on scroll event. You can take a look at a working version here.
;
(function () {
let loadedMovies = [];
let lastMoviePosition = 0;
let container = $('#movies');
$.getJSON("m.json", function (movies) {
if(movies && movies.length > 0){
loadedMovies = movies;
addMovies(10);
}
});
let addMovies = (n) => {
for(let i=0; i<n && lastMoviePosition < loadedMovies.length; i++){
var movie = '<a id="' + i + '" class="Movie" target="_blank" href="'+ limitMovies[lastMoviePosition].url + '/"><img src="'
+ limitMovies[lastMoviePosition].Poster + '"/></a>';
container.append(movie);
lastMoviePosition++;
}
};
$(window).scroll(function(){
addMovies(10);
});
})();
Add var limitMovies; into the first line of your code to make it globally accessible. Remove all var in front of other limitMovies declarations. Then do:
$(window).scroll(function(){
limitMovies+=10;
});
However, that wont answer your real question. Just increasing the counter wont work. You need to rerun the for loop to parse from that array. Also the scroll will fire a thousand times a second, you need another way of detecting it. May have a look at:
https://www.sitepoint.com/jquery-infinite-scrolling-demos/
You need to restructure your whole code, this wont fit into an answer on SO...

arrange the div in sequence format using javascript

I am working on scenario where when I enter number in the textbox i need generate dynamically div's. Actually I am struggling not aligned properly with the current div. Then I need to generate ID's for the div's. For this also code is available but the code not considered the default div as preview1 then it has to go on like preview2, preview3 so on. The div has to arrange sequence like first it has to show preview1......
var inputElement = document.getElementById("inputAdd_page");
var totalCount = 0;
inputElement.addEventListener('blur', function () {
var count = this.value;
// Gaurd condition
// Only if it is a number
if (count && !isNaN(count)) {
fragment = document.createDocumentFragment();
for (var j = 0; j < count; ++j) {
spancount = document.createElement('span');
prevPage = document.createElement('div');
navbutton = document.createElement('button');
preview_PageSize = document.getElementById('page');
navbutton.className = "div_navig";
navbutton.setAttribute('id', ['pag_navg' + totalCount]);
navbutton.innerHTML = [1 + totalCount];
spancount.className = "spanCount";
spancount.innerHTML = [1 + totalCount];
prevPage.className = "preview_windowSize";
prevPage.setAttribute('id', ['page' + totalCount]);
prevPage.appendChild(spancount);
prevPage.style.position = "absolute";
preview_PageSize.appendChild(prevPage);
//fragment.appendChild(prevPage);
fragment.appendChild(navbutton);
totalCount++;
}
inputElement.value = "";
document.body.appendChild(fragment);
}
});
Here is the fiddle Link
Thanks in advance.
Kindly help me.
if I get you right, change the javascript as follows:
//prevPage.style.position="absolute";
//preview_PageSize.appendChild(prevPage);
prevPage.style.width="100%";
preview_PageSize.parentNode.insertBefore(prevPage, preview_PageSize);
to improve positioning, you could apply a diffrent class to the child elements, like so:
prevPage.className = "preview_windowSize_element";
and use CSS:
.preview_windowSize_element {
position: absolute;
left: 31px;
top: 0px;
width: 100%;
height: 100%;
}
to start with page ID 1 you could modify your script:
prevPage.setAttribute('id', ['page' + (totalCount + 1)]);
Do you search something like this jsFiddle?.
I just add a left position in each div, because you set them to position:absolute.
So I added this line:
prevPage.style.left= (26 * totalCount) + "px";
I just put 26 like this, it will be the width of the button

Aligning Img tag side by with p tag below each image - CSS

I'm trying to align the image files side by with the image description right below it. This is my code below:
for (var i = 0; i < imgFilePathArray.length; i++) {
//html & css
var elementID = 'img' + (i+1).toString();
var element = document.createElement('img');
element.src = imgFilePathArray[i];
console.log(imgFilePathArray[i]);
element.id = elementID;
document.body.appendChild(element);
document.getElementById(elementID).style.width='50%';
element.style.height = 300;
element.style.display = 'inline-block';
if (i > 1) {
var errorP;
if (i%2==0) {
var frontErrorArray = errorInfo[buildVersion[buildCount]].split("$")[0];
var errorString = "";
errorString = frontErrorArray.toString();
//html & css
errorP = document.createElement('p');
var errorTextNode = document.createTextNode(errorString);
errorP.appendChild(errorTextNode);
}else{
var backErrorArray = errorInfo[buildVersion[buildCount]].split("$")[1];
var errorString = "";
errorString = backErrorArray.toString();
console.log(errorInfo[buildVersion[buildCount]].split("$")[1]);
//html & css
errorP = document.createElement('p');
var errorTextNode = document.createTextNode(errorString);
errorP.appendChild(errorTextNode);
buildCount = buildCount + 1;
}
document.body.appendChild(errorP);
};
}
The above execution gives me a layout like the image below:
I want the image to be by the side of each other and the text to be right below each image. Any idea what css styling should I amend to achieve that state?
Basically you need to have the divs that contain image and text have a css style float:left to achieve this.

Javascript: get an image width and than set a class

I want to analyse every image of an article and set an class for all images smaller/equal than perhaps 400px (and another class for images bigger than 400px) so that I can give them a specific style.
In jQuery it would be perhaps something like this
$('div#content').find('img').each(function () {
var $this = $(this), width = $this.width();
if (width <= 400) {
$this.addClass('small_img');
}
var $this = $(this), width = $this.width();
if (width > 400) {
$this.addClass('large_img');
}
});
But I need it to be in pure Javascript. As a stupid Journalist and Webdesigner I don't get it... If you could help me, I would be very thankful.
You mean something FAST and short like this?
window.onload = function() {
var n=document.getElementById('content').getElementsByTagName('img'),
i=n.length;
while(i--){
n[i].className = n[i].clientWidth > 400 ? 'large_img' : 'small_img' ;
}
};
See this fiddle for working example.
Also read this question on SO for selecting a method to fetch the (computed) width.
window.onload = function() {
var content = document.getElementById('content');
if (content) {
var img = content.getElementsByTagName('img');
for (var i = 0, count = img.length; i < count; i++) {
if (img[i].offsetWidth <= 400) {
img[i].className += ' small_img';
} else {
img[i].className += ' large_img';
}
}
}
};
Something like this should work:
// Find the parent container 'div#content'
var container = document.getElementById( "content" ),
// Find all images within the parent
images = container.getElementsByTagName( "img" ),
// Total number of images to check
len = images.length,
// Loop counter
i = 0,
// Represents the current image in the loop
image;
// Loop through all the images
for ( ; i < len; i++ ) {
// Access the current image
image = images[ i ];
// Use the ternary operator to assign one of two classes, based on width
image.className += ( image.clientWidth > 400 ) ? " large_img" : " small_img";
}
Hope that helps. Cheers!
var contentDiv = document.getElementById('content');
var imgs = contentDiv.getElementsByTagName('img');
for(i=0;i<img.length;i++){
var img = imgs[i];
if(img.clientWidth <= 400) img.className += " small_img"
else img.className += " large_img"
}

Categories