why is this button useless after 1 click? - javascript

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

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;
};

creating multiple blog posts using divs 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>

javascript span click event - using google icon

I want to do an event where the "span" tag is btn and the "main" tag disappears, but it doesn't work at all. Is using the Google icon a problem?
GenreBtn is an icon using Google icon.
let genreBtn = document.querySelector(".genreClick")
let mainBox = document.getElementsByTagName("main")
genreBtn.addEventListener("click", function() {
mainBox.style.display = "none";
})
Use document.querySelector(".main")
Html-
<span class="genreClick" type="button"> Btn </span>
<div class="main"> Hide this </div>
Javascript -
let genreBtn = document.querySelector(".genreClick")
let mainBox = document.querySelector(".main")
genreBtn.addEventListener("click", function() {
mainBox.style.display = "none";
})
In your code, mainBox is HTML collection, not HTML element.
You can try like this:
let mainBox = document.querySelector('main')
Or
let mainBox = document.getElementsByTagName('main')[0]
// main tag must be exist, if there isn't main tage, [ mainBox.style.display = "none" ] will return error.

How do I color a fontawesome icon with javascript?

I have the following fa-icon:
<div id="notification">
<div id="info">
<div class="service">
<i class="fas fa-music"></i>
<h1 class="name"></h1>
</div>
</div>
</div>
I tried the following to color it with javascript:
var Music = (swatches.DarkVibrant.getHex());
document.getElementById("info").getElementsByClassName("service")[0].style.color = Music;
// Gave i element this id
document.querySelector('#music').style.color = Music;
document.querySelector('.fas fa-music').style.color = Music;
However none of them work, how could I achieve this?
Edit: it seems like it only works outside my function, why does it not work when its inside?
// Works
document.querySelector('.fas').style.color = "blue"
function mainUpdate(type) {
if (type == "music") {
if (isplaying) {
document.querySelector('.name').innerHTML = "Now playing";
document.querySelector('.details').innerHTML = "• " + album;
document.querySelector('.song').innerHTML = title;
document.querySelector('.artist').innerHTML = artist;
var milli = new Date().getMilliseconds();
var albumart = document.querySelector("#artworkImage");
albumart.src = "/var/mobile/Documents/Artwork.jpg?" + milli;
albumart.addEventListener('load', function () {
var vibrant = new Vibrant(albumart);
var swatches = vibrant.swatches()
for (var swatch in swatches)
if (swatches.hasOwnProperty(swatch) && swatches[swatch]) {
var Name = (swatches.DarkVibrant.getHex());
var Music = (swatches.DarkVibrant.getHex());
}
document.querySelector('.name').style.color = Name; // Works
document.querySelector('.fas').style.color = "blue" // Doesnt work
});
}
}
}
Since 5.0 uses SVG try
document.querySelector('.fas fa-music').style.fill = Music;
If this does not work then you will have to select SVG inside and apply rule in it
Do something like
document.querySelector('.fa.fa-sign-in').style.color = "green"
You have a mistake in your selector. For your case, the correct line to modify the styles will be
document.querySelector('.fas.fa-music').style.color = "green"
Change "green" to your color
Did you try the following code?
document.querySelector('#info .service .fa-music').style.color = Music;
This one should also work:
document.querySelector('.fas.fa-music').style.color = Music;
It seems that you made a small mistake by writing ('.fas fa-music').

How To Create And Assign And Onclick Element To Another Element Created In JS

So, I am trying to make an element and then assign an onclick to it through JS.
Here is my code so far:
HTML
<div id = "Programs" onclick = "Cpb()">Programs</div>
JS
function Cpb() {
document.getElementById("AllBody").innerHTML = "";
var rh = document.createElement("h2");
var rht = document.createTextNode("Recent Programs");
rh.id = "Recentt";
var rh1 = document.createElement("h4");
var rh1t = document.createTextNode("test");
rh1t.onclick = window.open('website');
rh1.appendChild(rh1t);
rh.appendChild(rht);
}
So does anybody know how I can do this?
This javascript worked for me:
let h4Node = document.createElement("H4");
h4Node.innerHTML = "4th Header";
h4Node.onclick = function (){
alert('Oi!');
};
document.getElementById("demo").appendChild(h4Node);
Html:
<div class="demo"></div>
It will put an h4 element with an onclick event listener inside the demo div.
I think you want addEventListener.
Example:
rh1t.addEventListener('click', myHandlerFunction);
function myHandlerFunction () {
// ...
}
You can continue using onclick as you have in your code. But you'll need to do as I've done above and assign a function reference to it. Like this:
rh1t.onclick = myHandlerFunction;
function myHandlerFunction () {
window.open('website');
}

Categories

Resources