any idea why the div doesn't toggle?
I tried also to recall with html, i think i'm missing something, but i don't know what, to me looks ok, but for sure something is missing,
albums.forEach((album) => {
html += `<div class="user"><h2>User ${album.id} Album</h2>`;
let albumPhotos = photos.filter(p => p.albumId == album.id);
html += `<div>`
albumPhotos.forEach(photo => {
html += `<div id="myDIV">
<img src="${photo.thumbnailUrl}">
</div>
`;
});
html += '</div>';
});
// i call back the container set in html
let container = document.querySelector(".container");
container.innerHTML = html;
let container2 = document.querySelector(".button");
container.innerHTML = html;
}
// function recall
renderUsers();
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
You are adding <div id="myDIV"> for each photo, but you're supposed to have unique ids on the page.
You can't have divs with the same id - they should be different. In your case you cloud use class and not id.
Is this the kind of behaviour you're looking for?
<div class="container"></div>
<button class="button" onclick="toggleImages()">Toggles Images</button>
<script>
let html = '';
let albumPhotos = [1,2,3,4,5,6,7];
html += `<div>`;
albumPhotos.forEach(photo => {
html += `<div class="myDIV"><p>${photo}</p></div>`;
});
html += '</div>';
let container = document.querySelector(".container");
container.innerHTML = html;
let container2 = document.querySelector(".button");
container.innerHTML = html;
function toggleImages() {
var x = document.getElementsByClassName("myDIV");
for (let elem of x) {
if (elem.style.display === "none") {
elem.style.display = "block";
} else {
elem.style.display = "none";
}
}
}
Related
I'm not sure if is this what i need but i think its neccesery. Propably i need add another condition to this line
const div = document.querySelector(`#result_${i}`);
I have simple .js file with array of object. Currently every object has question, answer. I would like to expand it by "text" where i would tell some details about results etc.
//For Text
const text = document.createElement("div");
text.id = "text_" + i;
text.style.display = "none";
text.classList.add("pokus");
text.innerHTML = ex.text;
card.appendChild(text);
Logic is same as for answer. I can see it in the DOM but it's it's not showing for user. I think the reason is missing condition in querySelector? If yes. How can i add another? I tried (`#result_${i}, #text_$(i)`) or (`#result_${i}`, `#text_${i}`);
Whole code.
import("./Objects/" + selectedPage + ".js")
.then((array) => {
const { examples } = array;
console.log(array);
function toggle(i) {
const div = document.querySelector(`#result_${i}`);
if (div.style.display !== "none") {
div.style.display = "none";
} else {
div.style.display = "block";
}
}
const container = document.querySelector("#examples-container");
examples.forEach((ex, i) => {
const card = document.createElement("div");
card.classList.add("card");
const example = document.createElement("div");
example.classList.add("example");
example.innerHTML = ex.question;
card.appendChild(example);
//For Button
const button = document.createElement("button");
button.classList.add("toggle");
button.innerHTML = "výsledek";
button.addEventListener("click", () => toggle(i));
card.appendChild(button);
//For answer
const result = document.createElement("div");
result.id = "result_" + i;
result.style.display = "none";
result.classList.add("result");
result.innerHTML = ex.answer;
card.appendChild(result);
//For Text
const text = document.createElement("div");
text.id = "text_" + i;
text.style.display = "none";
text.classList.add("pokus");
text.innerHTML = ex.text;
card.appendChild(text);
// Add the card to the container
container.appendChild(card);
});
})
.catch((err) => {
console.log(err);
});
Im not 100% sure I understand your question, but right now you're using QuerySelector and it will only return the first element.
If you want to select multiple elements use QuerySelectorAll / getElementByClassName and then loop over the list they return.
Use querySelectorAll
As you want to target more than 1 node (here result, text) you need to use querySelectorAll instead of querySelector
function toggle(i) {
const divs = document.querySelectorAll(`#result_${i}`,`#text_${i}`);
for (let div of divs) {
if (div.style.display !== "none") {
div.style.display = "none";
} else {
div.style.display = "block";
}
}
}
I've written a simple code that takes text from the input field, stores it as a string in an array and creates a div with that same text every time the "add" button is pressed.
Then there's a "remove" button, that removes the item from array if the input matches the item in the array.
I need a function to remove the previously created div with the same text inside as the current input.
E.g. if I type "book1" press "add" - array gets 'book1' as a first item and a div "book1" is created, "book2", "book3" and so on. If I type 'book2' and press remove, it gets removed from the array and a respective div should be removed.
That last function I just can't figure out.
let addBtn = document.getElementById("add-btn");
let removeBtn = document.getElementById("rmv-btn");
let bookArray = [];
addBtn.addEventListener("click", addBook);
removeBtn.addEventListener("click", removeBook);
let innerDiv = document.body.newDiv.innerHTML
function addBook() {
newBook = document.getElementById("input").value;
if (newBook != '') {
bookArray.push(newBook);
addElement();
clear();
console.log(bookArray);
} else {
clear();
console.log(bookArray);
}
}
function removeBook() {
inputBook = document.getElementById("input").value;
for (i = 0; i < bookArray.length; i++) {
if (inputBook.toString() === bookArray[i].toString()) {
bookArray.splice([i], 1);
console.log(bookArray);
removeElement()
return;
} else {
clear();
}
}
console.log(bookArray);
}
function clear() {
document.getElementById("input").value = "";
}
function addElement() {
let newDiv = document.createElement("div");
newDiv.innerHTML = newBook;
my_div = document.getElementById("mydiv");
document.body.appendChild(newDiv, my_div);
}
function removeElement() {
alert("this bit needs working out");//???
}
<input type="text" id="input" />
<button id="add-btn">Add</button>
<button id="rmv-btn">Remove</button>
<div id="mydiv"></div>
</div>
You need to change how you are adding the div because it adding it outside and not as a child of my_div
let addBtn = document.getElementById("add-btn");
let removeBtn = document.getElementById("rmv-btn");
let bookArray = [];
addBtn.addEventListener("click", addBook);
removeBtn.addEventListener("click", removeBook);
function addBook() {
newBook = document.getElementById("input").value;
if (newBook != '') {
bookArray.push(newBook);
addElement();
clear();
console.log(bookArray);
} else {
clear();
console.log(bookArray);
}
}
function removeBook() {
inputBook = document.getElementById("input").value;
for (i = 0; i < bookArray.length; i++) {
if (inputBook.toString() === bookArray[i].toString()) {
bookArray.splice([i], 1);
console.log(bookArray);
removeElement(i);
return;
} else {
clear();
}
}
console.log(bookArray);
}
function clear() {
document.getElementById("input").value = "";
}
function addElement() {
let newDiv = document.createElement("div");
// count number of children in mydiv
let count = document.getElementById("mydiv").childElementCount;
// add an id
newDiv.id = 'mydiv-' + count;
newDiv.innerHTML = newBook;
my_div = document.getElementById("mydiv");
my_div.appendChild(newDiv, my_div);
}
function removeElement(el) {
// remove html element from dom
let my_div = document.getElementById("mydiv");
my_div.removeChild(my_div.childNodes[el]);
}
A workaround to remove book by the input value by user:
Modify the addElement function to:
function addElement() {
let newDiv = document.createElement("div");
newDiv.innerHTML = newBook;
newDiv.setAttribute('data-book-name', newBook); //new added line | setting data attribute
my_div = document.getElementById("mydiv");
document.body.appendChild(newDiv, my_div);
}
removeElement will be:
function removeElement() {
document.querySelector('[data-book-name="'+ newBook +'"]')?.remove();
}
But this will remove first book in the DOM. If you want to remove all books with same name use:
function removeElement() {
var books = document.querySelectorAll('[data-book-name="'+ newBook +'"]');
if(books.length == 0) return;
books.forEach(x => x.remove())
}
I want to add an event on an element does doesn't exist in the original HTML (created with innerHtml). When i click nothing happens.
const btnRemove = document.getElementById("remove");
btnMow.addEventListener("click", function mow() {
if (sMow === true) {
reqServices.push("Mow Lawn");
service.innerHTML += `
<div class="v1">
<p class="v3-text">Mown Lawn <span id="remove">remove</span></p>
<p class="v3-dollar"><span>$</span>20</p>
</div>`;
sMow = false;
total += 20;
totalC();
}
});
btnRemove.addEventListener("click", function remove() {
alert("HELLO");
});
I want to add a click event on the element with id remove.
Another way to do that is creating the elements instead of use the HTML code and a later search. This maybe useful if you, for example, don't want to add an id to the remove tag
btnMow.addEventListener("click", function mow() {
if (sMow === true) {
reqServices.push("Mow Lawn");
var div = document.createElement("div");
div.className = "v1";
service.appendChild(div);
var p1 = document.createElement("p");
p1.className = "v3-text";
div.appendChild(p1);
var p1Text = document.createTextNode("Mown Lawn ");
p1.appendChild(p1Text);
var p1Span = document.createElement("span");
p1Span.setAttribute("id", "remove");
p1Span.innerText = "remove";
p1Span.addEventListener("click", function remove() {
alert("HELLO");
});
p1.appendChild(p1Span);
var p2 = document.createElement("p");
p2.className = "v3-dollar";
p2.innerHTML = "<span>$</span>20";
div.appendChild(p2);
sMow = false;
total += 20;
totalC();
}
});
As you can see, creating the elements allow you do whatever you want with it. It's longer but you can use a helper function like this:
function appendTag(parent, tagName, className) {
var tag = document.createElement(tagName);
if (className)
tag.className = className;
parent.appendChild(tag);
return tag;
}
And rewrite as:
btnMow.addEventListener("click", function mow() {
if (sMow === true) {
reqServices.push("Mow Lawn");
var div = appendTag(service, "div", "v1");
var p1 = appendTag(div, "p", "v3-text");
p1.appendChild(document.createTextNode("Mown Lawn "));
var p1Span = appendTag(p1, "span");
p1Span.setAttribute("id", "remove");
p1Span.innerText = "remove";
p1Span.addEventListener("click", function remove() {
alert("HELLO");
});
var p2 = appendTag(p1, "p", "v3-dollar");
p2.innerHTML = "<span>$</span>20";
sMow = false;
total += 20;
totalC();
}
});
btnMow.addEventListener("click", function mow() {
if (sMow === true) {
reqServices.push("Mow Lawn");
service.innerHTML += `
<div class="v1">
<p class="v3-text">Mown Lawn <span id="remove">remove</span></p>
<p class="v3-dollar"><span>$</span>20</p>
</div>`;
sMow = false;
total += 20;
totalC();
}
const btnRemove = document.getElementById("remove");
btnRemove.addEventListener("click", function remove() {
alert("HELLO");
});
});
var btnremove = document.getElementById("remove");
write this before starting click event
As you can see, 3 divs are created using JavaScript when their respective buttons are clicked. I pass their values and then use those to create the content. I am not sure if this is the best way... but anyway.
The problem is that the divs keep appending. I only want to show one div at a time, and I also want to disable the active div's button. I've seen that you can use something like document.querySelector('button[onclick]').disabled = true;, but I am unsure of how to make it dynamically work because it would have to be set to false once any of the other buttons are clicked.
Here is my JavaScript that is responsible for creating the content:
function showDiv(name) {
var selectedButton = name.value;
var div = document.createElement('div');
div.id = 'myDiv';
document.body.appendChild(div);
if (selectedButton === 'home') {
div.innerHTML = 'Hi, this is a test for the ' + selectedButton + ' div.';
} else if (selectedButton === 'about') {
div.innerHTML = 'Hi, this is a test for the ' + selectedButton + ' div.';
} else if (selectedButton === 'contact') {
div.innerHTML = 'Hi, this is a test for the ' + selectedButton + ' div.';
}
}
My JSFiddle: http://jsfiddle.net/wwen39o9/
I've updated your fiddle: http://jsfiddle.net/wwen39o9/3/
In short, add one div to the html:
<div id="myDiv"></div>
Give buttons a class navbutton:
Javascript:
function showDiv(me) {
$('.navbutton').prop('disabled', false);
$(me).prop('disabled', true);
$('#myDiv').html('Hi, this is a test for my ' + $(me).val() + ' div.');
}
Pure JS version without jQuery:
function showDiv(me) {
var div = document.getElementById('myDiv');
var buttons = document.getElementsByTagName('button');
for (var i = 0; i < buttons.length; i++) {
if (buttons[i].className == 'navbutton')
buttons[i].disabled = false;
}
me.disabled = true;
div.innerHTML = 'Test for ' + me.value;
}
A couple of ways to set an active button in a group of buttons:
If they are confined to a wrapper:
function setActive(selectedButton){
var parent = selectedButton.parentNode;
var children = parent.getElementsByTagName('button');
var child_ct = children.length - 1;
while (child_ct) {
children[child_ct].disabled = false;
child_ct--;
}
selectedButton.disabled = true;
}
Or by giving all a class like .nav-btn
function setActive(selectedButton) {
var parent = selectedButton.parentNode;
var children = parent.getElementsByClassName('nav-btn');
var child_ct = children.length - 1;
while (child_ct) {
children[child_ct].disabled = false;
child_ct--;
}
selectedButton.disabled = true;
}
A good way to swap out div:
Check if div exists. Replace content if so, create div if not.
function showDiv(content) {
var div = document.getElementById('the-div');
if (div) {
//May be better to remove children, then append content, but...
div.innerHTML = content
} else {
var the_div = document.createElement('div');
the_div.id = 'the-div';
the_div.innerHTML = content;
document.appendChild(the_div);
}
}
So:
function handleClick() {
setActive(this);
if (this.name === 'home') {
showDiv('Information about being home');
}
}
<button onclick="handleClick">
The append method should be call only if we did not found one.
Something like
function showDiv(name) {
var selectedButton = name.value;
var div = document.getElementById('myDiv');
if(!div) {
document.createElement('div');
div.id = 'myDiv';
document.body.appendChild(div);
}
We can check the number of div elements on page
Or why not to do it like following. At the beginning we have an empty div with id="myDiv" and then we are just changing its content with JavaScript. Have a look at JSFiddle example.
HTML
<button value="home" onclick="showDiv(this);">Home</button>
<button value="about" onclick="showDiv(this);">About</button>
<button value="contact" onclick="showDiv(this);">Contact</button>
<!-- create an empty div -->
<div id="myDiv"></div>
JavaScript
function showDiv(name) {
var selectedButton = name.value;
var div = document.getElementById('myDiv');
if (selectedButton === 'home') {
div.innerHTML = 'Hi, this is a test for the ' + selectedButton + ' div.';
} else if (selectedButton === 'about') {
div.innerHTML = 'Hi, this is a test for the ' + selectedButton + ' div.';
} else if (selectedButton === 'contact') {
div.innerHTML = 'Hi, this is a test for the ' + selectedButton + ' div.';
}
}
<script>
function selecteditems()
{
var i=1;
var val="";
while(i<=53)
{
if(document.getElementById('timedrpact'+i)!="")
{
val+=document.getElementById('timedrpact'+i).value;
document.getElementById('showselecteditems').innerHTML=val;
}
i++;
}
}
</script>
How to create a new div and add contents to it?In the above case i lost previous content due to innerHTML.I want new div each time for dynamically attach an image and the above variable val to it.
Thanks in advance.
Check this Demo
<div id="output" class="out">
</div>
window.onload=function(){
var output = document.getElementById('output');
var i=1;
var val="";
while(i<=3)
{
if(!document.getElementById('timedrpact'+i))
{
var ele = document.createElement("div");
ele.setAttribute("id","timedrpact"+i);
ele.setAttribute("class","inner");
ele.innerHTML="hi "+i;
output.appendChild(ele);
}
i++;
}
};
Look at document.createElement() and element.appendChild().
var newdiv = document.createElement("div");
newdiv.innerHTML = val;
document.getElementById("showselecteditems").appendChild(newdiv);
Because you will likely encounter this in the near future: You can remove any element with this code:
element.parentNode.removeChild(element);
Using createElement:
function selecteditems() {
var container = document.getElementById('showselecteditems');
for (var i=1;i<=53;i++) {
var fld = document.getElementById('timedrpact'+i);
if (fld) {
var div = document.createElement("div");
div.appendChild(document.createTextNode(fld.value));
container.appendChild(div);
}
}
}
Full version using cloneNode (faster) and eventBubbling
Live Demo
var div = document.createElement("div");
var lnk = document.createElement("a");
var img = document.createElement("img")
img.className="remove";
img.src = "https://uperform.sc.gov/ucontent/e14c3ba6e4e34d5e95953e6d16c30352_en-US/wi/xhtml/static/noteicon_7.png";
lnk.appendChild(img);
div.appendChild(lnk);
function getInputs() {
var container = document.getElementById('showselecteditems');
for (var i=1;i<=5;i++) {
var fld = document.getElementById('timedrpact'+i);
if (fld) {
var newDiv = div.cloneNode(true);
newDiv.getElementsByTagName("a")[0].appendChild(document.createTextNode(fld.value));
container.appendChild(newDiv);
}
}
}
window.onload=function() {
document.getElementById('showselecteditems').onclick = function(e) {
e=e||event;
var target = e.target||e.srcElement;
// target is the element that has been clicked
if (target && target.className=='remove') {
parentDiv = target.parentNode.parentNode;
parentDiv.parentNode.removeChild(parentDiv);
return false; // stop event from bubbling elsewhere
}
}
getInputs();
}
Syntax for dynamic create div:
DivId = document.createElement('div');
DivId.innerHtml ="text"