Dynamically create HTML using array from local storage [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am trying to retrieve a title, description and image from local storage that I saved from a form but I am not sure how to dynamically create HTML to display it.
function readData() {
var formData={};
formData.title = document.getElementById("title").value;
formData.desc = document.getElementById("desc").value;
formData.img= document.getElementById("img").files[0].name;
return formData;
}
function displayBlog(){
var retrievedObject =JSON.parse(localStorage.getItem("blogData"));
var blogs1 = '';
for (blogpost of blogpost1) {
blogs1 += '<div>' +
'<div class="card border-secondary mb-3">' +
'<h5 class="card-header"></p></h5>' +
'<div class="card-body">' +
'<div class="blog-post">' +
'<h2 class="blog-post-title"></h2><br>' +
'</p>' +
'</div>' +
'</div>' +
'</div>' +
'</div><br></br>'
}
document.getElementById("blogs").innerHTML = blogs1;
}
Update: ended up using
document.body.appendChild(btn);
after research

You can work with JavaScript DOM Elements, check theese functions document.creatElement() and node.appendChild().
So it would go something like this:
function displayBlog() {
var retrievedObject =JSON.parse(localStorage.getItem("blogData"));
var blogs1 = document.createElement('div'); // container div
for (blogpost of blogpost1) {
var parentDiv = document.createElement('div'); // create parent div
parentDiv.className = 'card border-secondary mb-3'; // set parent div class names
// then here you create yor child tags, for example:
var h5 = document.createElement('h5');
h5.className = 'card-header';
h5.innerHTML = blogpost.title; // set the title here from your variable
// and next you append your child tag to the parent:
parentDiv.appendChild(h5);
// then you go on building your desired structure...
// when done you append your parentDiv from this loop iteraction to your container variable
blogs1.appendChild(parentDiv);
}
// at the end you set your container HTML to this element
document.getElementById("blogs").innerHTML = blogs1.outerHTML;
}

Related

How can I assign unique ID to innerhtml element? [duplicate]

This question already has answers here:
How can I apply a variable as an element ID with JavaScript?
(5 answers)
How can I pass an element to a function from onclick?
(2 answers)
Closed 7 months ago.
I have this function:
function displayInputIntro() {
var submitbutton = document.getElementById('submitbutton')
var intro = document.getElementById('Intro')
var introNewSection = document.getElementById('intro-row')
introNewSection.innerHTML += '<div class="col-lg-5 mb-lg-0 mb-4" id="intro">';
submitbutton.style.display = ''
}
This function displayInputIntro() can be called multiple times, and it will insert this new section into the body of the HTML as many times as one decides to do so. Problem is, I want to add a unique identifier, so that if I were to add something like this:
introNewSection.innerHTML += '<div class="col-lg-5 mb-lg-0 mb-4" id="intro">Remove Input';,
and click on Remove Input, then it would delete the input, not all of them.
I have tried something like this:
var uniqueID = new Date()
introNewSection.innerHTML += '<div class="col-lg-5 mb-lg-0 mb-4" id="' + uniqueID '"'>Remove Input';, and click on `Remove Input`, then it would delete the input, not all of them.
but that doesn't work. How can I do this?
you are passing an string to html code, not the real JS variable.
You can try something like this thant I found in How can I apply a variable as an element ID with JavaScript?:
var id = new Date();
var html ='<li id="' + id + '">'
+ '<input type="image" id="' + id + '" src="images/subtract.png" onclick="javascript:deleteProduct(this.id)" href="#">'
+ id
+ '</li>';

How to get and track a div height in a innerHTML string? Is that possible?

So with each iteration, the div, "activityItems" is getting bigger. What I'm trying to do is track the height of the div and make sure it doesn't exceed the page height(PDF). Based on the height of the div I want to put a page-break when it exceeds specified height limit. I know the PDF is going to be a height of 792 px. However, I want to put a page-break a little bit before that. Anyway, my question is how do I get and track the height of the div through each iteration from an innerHTML string?
The following is a code snippet.
Also, if there is a jQuery solution, I will accept that too.
var html = ''
var webElement = document.createElement('div');
webElement.id = 'items';
for (i=1; i< checlboxes.length; i++)
{
if (checkboxes[i].checked)
{
var OfficeName = row.cells[4].innerHTML;
var Summary = row.cells[8].innerHTML;
var Activities = row.cells[10].innerHTML;
html += '<br/>';
html += '<div class="row"><div class="col-md-6" style="display:inline-block; font-weight:bold">' + SummaryTitle + ' FROM ' + OfficeName + ': </div></div>'
html += '<div class="row"><div class="col-md-6" style="display:inline-block; text-align:justify">' + ActivityDetails + '</div></div>'
html += '<br/>'
webElement.innerHTML += '<div id="activityItems">' + html + '</div>';
}
}
Yes, it's definitely possible to track and get a div height.
First of all, you can get the height of the div by using attributes of dom element like the following.
clientHeight : just includes the padding of the div
offsetHeight : just includes the padding and border of the div
And you can also use getBoundingClientRect function of the element like this.
const ele = document.getElementById("myDiv")
let rect = ele.getBoundingClientRect()
console.log("height: " + rect.height)
That's it and in terms of track, you can use just a kind of timer or thread. may setTimeOut function in javascript.
"...how do I get and track the height of the div through each iteration..."
Track individual element mutations with MutationObserver. It allows you to track when the various changes are made to an element.
The below code sets up an observer on your div and reports the height as it grows. You can replace the console log with a function call that builds in your page break at that point.
EDIT: I realized that multiple elements rendered in a list will not fire the observer due to the async nature of the event. So I added a timeout in order to allow the observer to fire between each mutation. I also added more than one checkbox for clarity.
Then, you can either stop the observer (with .disconnect()) or allow it to continue listening for more changes.
var html = '';
var webElement = document.getElementById('items');
var checkboxes = document.querySelectorAll('[type=checkbox]');
const observer = new MutationObserver(callback);
observer.observe(webElement, {
attributes: true,
childList: true,
subtree: true
});
checkboxes.forEach(cb => {
setTimeout(() => {
html = '';
if (cb.checked) {
var OfficeName = "office name";
var SummaryTitle = "summary";
var Activities = "acvities";
html += '<br/>';
html += '<div class="row"><div class="col-md-6" style="display:inline-block; font-weight:bold">' + SummaryTitle + ' FROM ' + OfficeName + ': </div></div>'
html += '<div class="row"><div class="col-md-6" style="display:inline-block; text-align:justify">' + Activities + '</div></div>'
html += '<br/>'
webElement.innerHTML += '<div id="activityItems">' + html + '</div>';
}
}, 0);
});
function callback(mutationsList, observer) {
for (const mutation of mutationsList) {
if (mutation.type === 'childList') {
console.log('Item div height: ', mutation.target.getBoundingClientRect().height);
}
}
};
<input type="checkbox" checked>
<input type="checkbox" checked>
<div id="items"></div>

How to store an id from an API in a variable so that on an on click it can be used to locate information? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
On an on click function I have album images from an API appear. When clicking on the album image I have an overlay with the image.
I am trying to attach other information about the album to the overlay. Is it possible to store the albums id in a variable so that on click just the information from one particular album is displayed? I can get all of the ids in this function as a variable, but can not work out how to store each one as an individual variable, to use on the on click function. Any suggesstions are appreciated.
function displayAlbums(data) {
var html = '<ul>';
$.each(data.tracks, function(i, eachAlbum) {
html += '<li class="albumImage">';
html += '<img src="' + eachAlbum.album.images[0].url +
'">';
html += '</li>';
var id = eachAlbum.album.id;
console.log(id); // all albums id's are showing
in console
}); // closes each
html += '</ul>';
$("#albumImages").html(html);
} //closes displayAlbums function
Store as data attribute on each <img> or <li>
html += '<img data-album_id="' +eachAlbum.album.id +'" src="' + eachAlbum.album.images[0].url + '">';
Then a click handler can access it directly from the element itself
$("#albumImages").on('click', '.albumImage img', function(){
console.log('album id=', $(this).data('album_id'));
})
You can use data-id attributes on img or li, whichever makes sense inside your $.each and access them in onclick listener, like this:
function displayAlbums(data) {
var html = '<ul>';
$.each(data.tracks, function(i, eachAlbum) {
html += '<li class="albumImage">';
html += `<img src="${eachAlbum.album.images[0].url}" data-id="${eachAlbum.album.id}">`;
html += '</li>';
var id = eachAlbum.album.id;
console.log(id); // all albums id's are showing in console
}); // closes each
html += '</ul>';
$("#albumImages").html(html);
}
More on using data attributes(MDN)
More on template literals, as used here
html += `<img src="${.....`
you could add the id as a data-id attribute, so it would look like this:
html += '<img src="' + eachAlbum.album.images[0].url + '" data-id="' + eachAlbum.album.id + '">';

Why doesn't my local storage work? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I am trying to localStore the history but it does not work. I tried JSON.stringify and a script called JStorage but I couldn't get either to work.
function updateHistory(video) {
getHistory();
blacklist[video["id"]] = true;
myhistory.push(video);
var html = "<li class=\"history\">" +
"<img class= \"img-rounded\" src=\"{0}\"/>" +
"<p><b title=\"{2}\"><a class=\"extendedLink\" href=\"javascript:watchHistoricVideo(\'{1}\');\"><span></span>{2}</a></b><br>" +
"by {3}<br>" +
"{4} | {5} views</p>" +
"</li>";
$("#myhistory").prepend(html.format(video["thumbnail"],
video["id"],
video["title"],
video["uploader"],
video["length"],
video["views"]));
saveHistory();
}
function saveHistory() {
localStorage.setItem(myhistory, myhistory.innerHTML);
}
(The alert does show up)
function getHistory() {
localStorage.getItem(myhistory);
alert("working");
}
The point is, instead of storing the html part you better store the video object instead, you can store videos based on their id, and instead of array use javascript object:
function setVideo(video) {
var videos = JSON.parse(localStorage.getItem("myhistory") || "{}");
videos[video["id"]]=video;
localStorage.setItem("myhistory", JSON.stringify(videos));
}
function getVideos() {
var myhistory = localStorage.getItem("myhistory");
if(!myhistory) return {};
else return JSON.parse(myhistory);
}
function getVideo(id) {
var myhistory = localStorage.getItem("myhistory");
if(!myhistory) return null;
var videos = JSON.parse(myhistory);
return videos[id] || null;
}
now you can use getVideo to retrieve the video object by id.you can separate the part which shows the video, like:
function showVideo(video) {
blacklist[video["id"]] = true;
var html = "<li class=\"history\">" +
"<img class= \"img-rounded\" src=\"{0}\"/>" +
"<p><b title=\"{2}\"><a class=\"extendedLink\" href=\"javascript:watchHistoricVideo(\'{1}\');\"><span></span>{2}</a></b><br>" +
"by {3}<br>" +
"{4} | {5} views</p>" +
"</li>";
$("#myhistory").prepend(html.format(video["thumbnail"],
video["id"],
video["title"],
video["uploader"],
video["length"],
video["views"]));
}
let's say you want to show the whole videos in the history:
var videos = getVideos();
for(var id in videos){
showVideo(videos[id]);
}

Add link to this JavaScript code [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
I have the following javascript code for a rotating image. Those images are in a separate folder from the javascript. I want to link the rotation itself to another page. All images will go to the same link. The current code works great but I just don't know where I add the a href code or its syntax.
// JavaScript Document
//
// Type the number of images you are rotating.
NumberOfImagesToRotate = 3;
FirstPart = '<img src="domain/rotatingimages';
LastPart = '.gif" height="250" width="388">';
function printImage() {
var r = Math.ceil(Math.random() * NumberOfImagesToRotate);
document.write(FirstPart + r + LastPart);
}
Try this format
<img src='image_src' border="0"/>
It is up to you if you want to define the target attribute in <a> tag.
// JavaScript Document
//
// Type the number of images you are rotating.
var numberOfImagesToRotate = 3;
// Edit the destination URl here
var linkUrl = 'example.html';
// HTML-partials
var imgFirstPart = '<img src="domain/rotatingimages';
var imgLastPart = '.gif" height="250" width="388" border="0">';
var anchorFirstPart = '<a href="';
var anchorSecondPart = '">';
var anchorLastPart = '</a>';
function printImage() {
var r = Math.ceil(Math.random() * numberOfImagesToRotate);
document.write(anchorFirstPart + linkUrl + anchorSecondPart + imgFirstPart + r + imgLastPart + anchorLastPart);
}

Categories

Resources