I'm creating some elements using JS, and need to add a class to each item when clicked, but remove it from the non clicked items. I'm sure this is a quick one, but I can't get my head around it.
let data = {
label:label,
somethingElse:"test",
id:id
};
sidebarOptions.push(data);
let ul = document.querySelector(".page-sidebar__options");
sidebarOptions.forEach(sidebarOption => {
let li = document.createElement('li'),
button = document.createElement('button'),
title = document.createElement('span'),
price = document.createElement('span')
ul.appendChild(li);
li.appendChild(button);
button.appendChild(title);
button.appendChild(price);
title.innerHTML = sidebarOption.label + sidebarOption.id;
price.innerHTML = '[Price]';
button.onclick = (event) => {
button.classList.add('selected');
};
})
So find if you have a selected button and remove the class
const currentlySelected = ul.querySelector('button.selected');
if (currentlySelected) currentlySelected.classList.remove('selected');
Related
so i wrote this code that would create a list and then append an input to it on click. really simple. but the problem is it doesn't work and i have no idea why
here is the code:
function pushing() {
var li = document.createElement("li");
var inputValue = document.getElementById("inp").value;
var pushchild = document.createTextNode(inputValue);
li.appendChild(pushchild);
}
sub.addEventListener("click", pushing);
the id inp is an input id. thank you
Add this to the last line of your function. Append your newly created li element to the ul.
document.querySelectorAll(‘ul’).appendChild(newCreatedLi);
Your list item is never appended to a list element.
// Cache the elements,
// add the button listener,
// & focus on the input
const list = document.querySelector('ul');
const input = document.querySelector('#inp');
const sub = document.querySelector('#sub');
sub.addEventListener('click', pushing);
input.focus();
function pushing() {
const li = document.createElement('li');
const text = document.createTextNode(input.value);
li.appendChild(text);
// Adding the list item to the list element
list.appendChild(li);
}
<input id="inp" />
<button id="sub">Click</button>
<ul></ul>
Now I am doing a shopping cart in my project, when i click the add to cart button, then it will upload the data in localstorage, then i will create an element (product name, price, quantity and two increment and decrement button in the list) and this create process will be looped by the length of localstorage.
When I want to make click event on increment and decrement button, only the last row of increment and decrement button respond. For example, I have 3 rows in shopping cart, only the third row will show the proper result, the first two row have no response.
I would like to ask can you give me some suggestion, how to achieve my goal? Thanks!!!!!!!!!!!!!!
var ul = document.getElementById("cart")
for(var i=0;i<localStorage.length;i++){
var li = document.createElement("li");
var addBtn =document.createElement("BUTTON");
var dropBtn document.createElement("BUTTON");
addBtn.innerHTML = '+';
dropBtn.innerHTML = '-';
addBtn.id='addBtn'
var a = document.getElementById("addBtn")
addBtn.onclick = function(){
alert('here be addBtn');return false;
};
dropBtn.onclick = function(){
alert('here be dropBtn');return false;
};
ul.appendChild(addBtn);
ul.appendChild(dropBtn);
ul.appendChild(li);
}
You need to make some changes to work as expected:
Not to search/find button when you have its reference.
append a button to list i.e. li not to ul (Thanks CBroe).
I've taken some assumption like the localStorage length as 3 and added the text of the cart button.
const ul = document.querySelector("ul#cart");
for (var i = 0; i < 3; i++) {
var li = document.createElement("li");
var addBtn = document.createElement("BUTTON");
var dropBtn = document.createElement("BUTTON");
var text = document.createElement("span");
text.textContent = ` item${i+1} `
addBtn.innerHTML = '+';
dropBtn.innerHTML = '-';
addBtn.id = `addBtn${i+1}`;
dropBtn.id = `dropBtn${i+1}`;
addBtn.addEventListener('click', e => {
alert(`here be addBtn with id ${e.target.id}`);
})
dropBtn.addEventListener('click', e => {
alert(`here be dropBtn with id ${e.target.id}`);
})
li.appendChild(addBtn);
li.appendChild(text);
li.appendChild(dropBtn);
ul.appendChild(li);
}
<ul id="cart"></ul>
I have a for of loop that has 3 event listeners on links from a drop down menu. The first clears the div with the id 'kittyBox', the second adds an object to the div 'kittyBox', the third closes the menu.
My problem is that instead of the actual input of the object appearing, [object, Object] appears. How do I get the actual input to appear?
let kittyBox = document.getElementById('kittyBox')
function clearContainer() { kittyBox.innerHTML = '' }
function addBoo() { kittyBox.append(boo) }
class Cat {
constructor(name, source) {
this.box = document.createElement('div');
kittyBox.append(this.box);
this.header = document.createElement('h1');
this.header.innerHTML = name;
this.photo = new Image(400, 400);
this.photo.src = source;
this.count = document.createElement('span');
this.box.append(this.header, this.photo);
this.header.append(this.count);
this.photo.onclick = counter;
function counter() {
score++;
document.querySelector('span').textContent = ` ` + score;
}
}
}
let boo = new Cat('Boo', './img/boo.jpg')
for (let link of links) {
link.addEventListener('click', clearContainer)
link.addEventListener('click', () => { if (links[0]) { addBoo() } }
link.addEventListener('click', () => menu.classList.toggle('slide-menu'))
I would like boo(div, h1, and image) to appear.
the append() method inserts a set of Node ob jects or DOMString objects. In your case, you will have to create HTML elements of the object. Then append the newly created HTML elements to the kittyBox element.
For example:
const catElem = document.createElement("div");
const catImg = document.createElement("img");
catImg.src = boo.photo.src;
catElem.append(catImg);
kittyBox.append(catElem);
I'm new to all of this so please bear with me...
I have a Bootstrap 3 modal window that opens up with a few form fields in it. I've managed to append the form fields to the DOM after you click Submit New Appointment. Buuut I can't seem to figure out how to close the modal window after the fields have been appended to the DOM. I'm hoping to achieve this by writing some good ole vanilla JavaScript. (Unfortunately I cannot use any jQuery.)
I have included the vanilla JavaScript code below. (It basically creates an appointment card from the info inputed from the form thats in the modal and then it gets displayed as a card into the DOM.)
Thanks for taking a look!
var form = document.getElementById('addForm');
// element to append the new carousel item to
var itemList = document.querySelector('.carousel-inner');
// form submit event
form.addEventListener('submit', addItem);
// form delete event
itemList.addEventListener('click', removeItem);
// add item Function
function addItem(e) {
e.preventDefault();
// get input value in the modal
var newItem = document.getElementById('item').value;
var newItemTwo = document.getElementById('time').value;
var newItemThree = document.getElementById('name-of-client').value;
var newItemFour = document.getElementById('phone-number-client').value;
var newItemFive = document.getElementById('acces-notes').value;
// create a new li element with the text grab from above
var li = document.createElement('li');
/**
* Set the correct class name for the carousel to work
*/
// li.className = 'list-group-item';
li.className = 'item';
li.style.maxWidth = '95%';
li.style.border = 'solid 1px #d3d3d3';
li.style.padding = '10px';
li.style.height = '150px';
li.style.marginRight = '12%';
li.style.marginLeft = '12%';
li.style.fontWeight = '500';
li.style.fontSize = '14px';
// console.log(li)
// create a new p element with the text grab from above
var pOne = document.createElement('p');
pOne.className = 'items';
pOne.style.fontSize = '12px';
pOne.style.fontWeight = '400';
pOne.style.marginTop = '5px';
var pTwo = document.createElement('p');
pTwo.className = 'items';
pTwo.style.fontSize = '12px';
pTwo.style.fontWeight = '200';
console.log(pTwo)
var pThree = document.createElement('p');
pThree.className = 'items';
pThree.style.fontSize = '12px';
pThree.style.fontWeight = '200';
console.log(pThree)
var pFour = document.createElement('p');
pFour.className = 'items';
pFour.style.fontSize = '12px';
pFour.style.fontWeight = '200';
console.log(pFour)
// add text node with input value
li.appendChild(document.createTextNode(newItem));
pOne.appendChild(document.createTextNode(newItemTwo));
pTwo.appendChild(document.createTextNode(newItemThree));
pThree.appendChild(document.createTextNode(newItemFour));
pFour.appendChild(document.createTextNode(newItemFive));
// create delete BUTTON
var deleteBtn = document.createElement('button');
deleteBtn.style.width = '50px';
deleteBtn.style.float = 'right';
deleteBtn.style.height = '50px';
deleteBtn.style.borderRadius = '50%'
deleteBtn.style.border = 'solid 1px red';
deleteBtn.style.backgroundColor = 'white';
deleteBtn.style.color = 'red';
// add the classes to the delete BUTTON
deleteBtn.className = "btn btn-danger btn-sm float-right delete";
// append the text node
deleteBtn.appendChild(document.createTextNode('X'));
// append delete button into the LI
li.appendChild(deleteBtn);
// append li to list.
/**
* insert the new element at the beginning of the itemList element, not at the end
*/
// itemList.appendChild(li);
itemList.insertBefore(li, itemList.firstChild);
// append p elements into LI; (not sure if this is the best way but its working)
li.appendChild(pOne);
li.appendChild(pTwo);
li.appendChild(pThree);
li.appendChild(pFour);
li.appendChild(pFive);
}
// remove item function
function removeItem(e) {
console.log(e.target)
if (e.target.classList.contains('delete')) {
if (confirm('Are you sure bro?')) {
var li = document.querySelector('.item.active');
itemList.removeChild(li);
document.querySelector('.item').classList.add('active')
}
}
}
Image of the modal from Bootstrap 3
Here is my code: http://jsfiddle.net/H5bRH/
Every time I click on the submit button, it should insert what I typed into a new li item.
But instead of that, it inserts what I typed the first time PLUS the new value that I typed. Play with my jsfiddle to see what I mean.
How do I fix this so that it only adds what the user inputs into the form?
I assume there's something wrong here:
function saveTweet() {
var tweet = document.getElementById("tweet");
var tweetName = tweet.value;
var li = document.createElement("li");
li.innerHTML = tweetName;
var ul = document.getElementById("tweets");
ul.appendChild(li);
}
You have attached 2 click event to save button.
button.onclick = saveTweet;
Using jQuery $("#saveTweet").click(function ()
$("#saveTweet").click(function () {
var tweet = document.getElementById("tweet");
var tweetName = tweet.value;
var li = document.createElement("li");
li.innerHTML = tweetName;
var ul = document.getElementById("tweets");
ul.appendChild(li);
$("li").slideDown("fast");
});
JSFiddle
Why not just reduce all that code to :
$("#saveTweet").click(function () {
$('#tweets').append('<li>' + $("#tweet").val() + '</li>')
$("li").slideDown("fast");
});
jsFiddle example
Instead of having two click handlers for the #saveTweet button, move the slideDown call to your saveTweet function.
function saveTweet() {
var tweet = document.getElementById("tweet");
var tweetName = tweet.value;
var li = document.createElement("li");
li.innerHTML = tweetName;
var ul = document.getElementById("tweets");
ul.appendChild(li);
$("li").slideDown("fast");
}
It happens because you bind two click handlers on the #saveTweet element.
One to add the content, and one to animate the li elements..
In your case the animated one is occuring first and the appending second.. so you always animate the previously added element...
Since you use jQuery anyway, why not use that for all your interactions ?
$(function () {
var button = $("#saveTweet");
button.on('click', function () {
var tweet = $("#tweet"),
ul = $("#tweets"),
tweetName = tweet.val(),
li = $('<li>', {html: tweetName});
ul.append(li);
li.slideDown("fast");
});
});
Demo at http://jsfiddle.net/gaby/Y9cY3/1/