creating multiple blog posts using divs javascript - javascript

I used the following code that allows for creating a "blog post" that is composed of multiple divs. I want that every time I click the button a new blog post is created but what actually happens is that no new posts are created and the only thing that changes is the content of the divs, to be specific the content of contentDiv. In other words, the user input or the post content is the only thing that changes.
const BtnAdd = document.getElementById("buttonpost1");
BtnAdd.addEventListener("click", AddNew);
function AddNew() {
var newhtml = document.getElementById("postbox").value;
sessionStorage.setItem("page1content", newhtml);
document.getElementById("postbox").value = "";
location.reload();
return false;
}
var newhtml2 = document.getElementById("profilecontent").innerHTML;
var newhtml3 = document.getElementById("underpost").innerHTML;
var newhtml4 = document.getElementById("commentcontent").innerHTML;
sessionStorage.setItem("usercontent" , newhtml2);
sessionStorage.setItem("belowcontent", newhtml3)
sessionStorage.setItem("commentcont", newhtml4)
const contentDiv = document.createElement("div");
const userDiv = document.createElement("div");
const lowerDiv = document.createElement("div");
const commentDiv = document.createElement("div");
const bigDiv = document.createElement("div");
bigDiv.classList.add("div-shadow");
contentDiv.classList.add("div-shadow2");
userDiv.classList.add("div-shadow3");
lowerDiv.classList.add("div-shadow4");
commentDiv.classList.add("div-shadow5");
userDiv.innerHTML = sessionStorage.getItem("usercontent");
contentDiv.innerHTML = sessionStorage.getItem("page1content");
lowerDiv.innerHTML = sessionStorage.getItem("belowcontent");
commentDiv.innerHTML = sessionStorage.getItem("commentcont");
var cWrapper = document.getElementById("contentwrapper");
bigDiv.appendChild(contentDiv);
bigDiv.appendChild(userDiv);
bigDiv.appendChild(lowerDiv);
bigDiv.appendChild(commentDiv);
cWrapper.appendChild(bigDiv);
what changes should I make to allow for the creation of a new blog post each time the user clicks the button of id buttonpost1 and not just override the content of the existing post (divs)?

I don't see any appendChild in your AddNew function, you need to create and append new elements each time the AddNew function gets called.
This is a minimal example:
const container = document.querySelector('#container');
const button = document.querySelector('button');
button.addEventListener('click', () => {
addNewPost();
});
function addNewPost() {
const newPost = document.createElement('div');
newPost.innerText = 'New Post';
container.appendChild(newPost);
}
<button type="button">Add New Post</button>
<div id="container"></div>

Related

Render an element inside literal templates with a EventListener

I'm trying to insert an element with an EventListener at a certain point of an element. I can achieve this via appendChild but I want to insert it at a certain point. Like this:
const divT = () => {
const div = document.createElement("div");
const div_inside = document.createElement("div");
div_inside.addEventListener("click", () => {console.log("div_inside")});
div_inside.innerHTML = "INSIDE";
div.innerHTML = ` TEST ${div_inside.outerHTML} TEST `;
return div;
};
document.body.appendChild(divT());
The main problem is the outerHTML does not contain the information of the listener. There is a method to render the HTML with the listener still active?
Thanks in advance
Find a workaround using insertAdjacentElement and attaching an empty div:
const divT = () => {
const div = document.createElement("div");
const div_inside = document.createElement("div");
div_inside.innerHTML = "Hello World";
div_inside.addEventListener("click", () => {console.log("div_inside")});
div.innerHTML = ` TEST <div id="inside"></div> TEST `;
const div_s = div.getElementsByTagName('div')
div_s[0].insertAdjacentElement('beforebegin', div_inside)
return div;
};

why is this button useless after 1 click?

I want to add a div (with class="book-card") each time I click the button (with class="add-book-btn". With the code below, when i click the button for first time, it works. But then the something is wrong and the button seems it's not working.
HTML:
<fieldset class="self">
<legend class="self-title">curently reading</legend>
<button class="add-book-btn"><i class="fas fa-plus plus-icon"></i></button>
</fieldset>
JS:
const selfs = document.getElementsByClassName("self");
const addBookBtn = document.getElementsByClassName("add-book-btn");
addBookBtn[0].addEventListener("click", function() {
selfs[0].innerHTML += `<div class="book-card"></div>`;
console.log(selfs[0]);
});
Using the code of #Dylan Cadd and focusing on my elemnts it worked. But I can't understand what's the differece
JS:
const selfs = document.getElementsByClassName("self");
const addBookBtn = document.getElementsByClassName("add-book-btn");
addBookBtn[0].addEventListener("click", function() {
let innerDiv = document.createElement('div');
innerDiv.className = 'book-card';
selfs[0].appendChild(innerDiv);
});
Try this code:
const selfs = document.getElementsByClassName("self");
function add_card() {
const addBookBtn = document.getElementsByClassName('add-book-btn');
addBookBtn[0].addEventListener('click', function(){
selfs[0].innerHTML += `<div class="book-card"></div>`;
console.log(selfs[0] );
add_card();
});
};
add_card();
<fieldset class="self">
<legend class="self-title">curently reading</legend>
<button class="add-book-btn">Click</button>
</fieldset>
I found a solution that is working for me. Instead of editing the innerHTML, I am dynamically creating the div with the classname and appending it to the main fieldset.
const selfs = document.querySelector(".self");
const addBookBtn = document.querySelector(".add-book-btn");
addBookBtn.addEventListener("click", function() {
let innerDiv = document.createElement('div');
innerDiv.className = 'book-card';
selfs.appendChild(innerDiv);
console.log(selfs);
});
This solution works for me, let me know if it doesn't for you

Rendering Info Cards and modal box with forLoop only outs the last result in one of the fields

I am practising vainilla JS and DOM manipulation. I am rendering a group of cards populated with data from an Object (that I fetch from an API, but this happens also if i do it in local).
I get to render the cards,all good, and create a button in each of them, that triggers a Modal box made with Bootstrap, with some additional information about that item.
The problem I have is that when I click on the button, the modal box only displays the information from the last element of the Object.
The function i wrote is as follows :
function createCards(data) {
let cardContainer = document.getElementById('cardContainer');
let modalTitle = document.getElementById('modalTitle');
let modalBody= document.getElementById('modalBody');
for (let i = 0; i < data.length; i++) {
let divCard = document.createElement('div');
divCard.setAttribute('class', 'card');
let imgFish = document.createElement('img');
imgFish.setAttribute('class', 'card-img-top');
let imgUrl = data[i]['Species Illustration Photo'].src
// console.log(imgUrl)
imgFish.setAttribute('src', imgUrl);
let divCardBody = document.createElement('div');
divCardBody.setAttribute('class', 'card-body');
let hCardTitle = document.createElement('h5')
hCardTitle.innerHTML = data[i]['Species Name'];
let pCardText = document.createElement('p');
pCardText.setAttribute('class', 'card-text');
pCardText.innerHTML = 'Kcal = ' + data[i].Calories
let aInfoButton = document.createElement('a');
aInfoButton.setAttribute('class', 'btn btn-primary');
aInfoButton.setAttribute('href', '#');
aInfoButton.setAttribute('data-toggle', 'modal');
aInfoButton.setAttribute('data-target', '#myModal');
aInfoButton.innerHTML = 'Nutrional Info'
cardContainer.appendChild(divCard);
divCard.appendChild(imgFish);
divCard.appendChild(divCardBody);
divCardBody.appendChild(hCardTitle);
divCardBody.appendChild(pCardText);
divCardBody.appendChild(aInfoButton);
//fill in Modal box
aInfoButton.onclick = function () {
createModal(data);
}
}
console.log("createCards() run")
}
and then, the function to populate the modal box :
function createModal(data) {
let modalTitle = document.getElementById('modalTitle');
let modalBody= document.getElementById('modalBody');
for (let i = 0; i < data.length; i++) {
modalTitle.innerHTML = data[i]['Species Name'];
modalBody.innerHTML = data[i]['Cholesterol'];
}
}
I tried also wrapping the creation of those two innerHTML from the modal box inside a different function, thinking it was a problem of time needed to render each item, but it seems that the problem is different, and I can't see which one.
It looks like, at the bottom of your for-loop, you are overwriting the innerHTML every time.
modalTitle.innerHTML = data[i]['Species Name'];
modalBody.innerHTML = data[i]['Cholesterol'];
So when you exit the for loop, what ever iteration of data is last is the one that will be in the modal.
2 ways to go about fixing:
1.) create a modal specific to each card.
2.) add an eventListener to the button that will populate the correct info onclick

Making a comment to the DOM from a constructor function

I am trying to make function that will post comment that'll add a headline and a text-section, based on a constructor-object. #Title and #text are the two bars in which the text will go. #form is the button the event listens to. I can't seem to get it to work now. Ideas?
function commentPost (title, text){
this.title = $("title").val;
this.tekst = $("text").val;
}
var commentPosts = [];
var formular = $('#form');
formular.on('click', function getTarget(e) {
e.preventDefault();
var jsTitleInput = $('title').val;
var jsTextInput = $('text').val;
var newComment = new commentPost(jsTitleInput, jsTextInput);
commentPost.push(newComment);
console.log(newComment);
});

Dynamic img creation through a link without attaching multiple instances

I have a link that is attached with an "onclick" function. When pressed it attaches an img element into a separate div called "mediaBox". The problem I'm having is that if it's pressed multiple times then it attaches more instances of the img. How can I control this. I'm still new to JavaScript and I prefer to receive this answer in pure Javascript not jQuery, as I will cross that bridge after I have a full understanding of Javascript.
var rkf = document.getElementById("submenulinks").getElementsByTagName("li")[0];
rkf.onclick = function(){
var client = document.getElementById('client');
var description2 = document.getElementById('description2');
var role = document.getElementById('role');
var mediaBox = document.getElementById('mediaBox');
var thumb = document.getElementById("thumb");
var client2 = document.getElementById("client2");
var newImage = document.createElement("img");
client2.innerHTML = "Role - Applications";
client.innerHTML = "RKF Real Estate";
client2.innerHTML = "Role - Applications";
description2.innerHTML = "Quarterly Catalog of Exclusive Listings managed by RKF";
role.innerHTML = "Custom designed Cover and listings content. Tables were also utilized within Indesign. <br><br><b><i> Photoshop and Indesign</i></b>";
newImage.setAttribute("src", "../images/rkf_cover.jpg");
newImage.setAttribute("height", "500px");
newImage.setAttribute("width", "387px");
newImage.setAttribute("alt", "rkf");
newImage.setAttribute("href", "#");
mediaBox.style.backgroundImage = "none";
document.getElementById("mediaBox").appendChild(newImage);
newImage.style.display = "block";
newImage.style.marginLeft = "auto";
newImage.style.marginRight = "auto";
newImage.style.marginTop = "25px";
}
rkf.onclick = function(){
var client = document.getElementById('client');
...
...
...
// Remove the handler after it ran once.
this.onclick = null; // <<<<<========================
}
Since you do want to use jQuery in the future, it's equal to:
$('#submenulinks li:first').one('click', handler);

Categories

Resources