Having errors with on click function to show/hide content - javascript

I have two dynamically created components and Im working on a onClick function to show content. The problem that I am having is during the onClick event my code is showing all content. What I am looking for is when I click index 1 of my first component, I want to show index 1 of my second component and hide the rest and when I click on the next index, I show the next index of my second component. Appreciate any help or suggestions to make it better.
showContent(){
const container = document.querySelector('ne-card-slider').shadowRoot;
const wrapper = document.querySelector('ne-main-content').shadowRoot;
const card = container.querySelectorAll<HTMLElement>('.anchor');
const content = wrapper.querySelectorAll<HTMLElement>('.contentMain');
//console.log(content);
//console.log(card);
//console.log(card[1].getAttribute('href'));
//console.log(content[1].getAttribute('id'));
for (let i = 0; i < card.length; i++){
content[i].classList.remove('active');
if (card[i].getAttribute('href') === content[i].getAttribute('id')) {
content[i].classList.add('active');
}
}
}

let cardCount = 0;
showContent(){
const container = document.querySelector('ne-card-slider').shadowRoot;
const wrapper = document.querySelector('ne-main-content').shadowRoot;
const card = container.querySelectorAll<HTMLElement>('.anchor');
const content = wrapper.querySelectorAll<HTMLElement>('.contentMain');
if (cardCount === 0){ content[0].style.visibility = "visible"; cardCount++; }
else { content[cardCount].style.visibility = "visible"; cardCount++; }
}

Related

Creating a dynamic list using javascript

I have created a simple to do list which takes the value of the input and places it in a div and attaches some classes to them, everything works fine but how do I fix the for loop and make it work everytime and adds multiple divs under eachother instead of changing the existing one.
Here's my code:
let dynamicList = document.querySelector("#dynamic-list"),
dynamicDiv = document.createElement("div"),
dynamicClass = document.querySelector(".dynamic"),
circle = document.querySelector(".circle"),
paragraphTest = document.createElement("p"),
circleTest = document.createElement("div");
input.addEventListener("keypress", function(e){
value = input.value
if(e.key == "Enter"){
for(i=0; i<=dynamicList.children.length; i++){
dynamicList.insertBefore(dynamicDiv, dynamicClass.nextSibling)
let sibling = dynamicClass.nextSibling;
sibling.classList.add("dynamic")
sibling.appendChild(circleTest)
circleTest.classList.add("circle")
sibling.appendChild(paragraphTest)
paragraphTest.innerHTML = input.value
}
})
<div id="dynamic-list">
<div class="dynamic"><div class="circle"></div><p class="paragraph">some dummy text/p></div>
</div>
Here's what I mean:
https://imgur.com/a/Zgm48ze
That's what happens when I add text, it works perfectly. But when I add another text it overrides the first one instead of adding another div.
You should use createElement method every time you want to create that element. by just using it once, it will create only one, so if you change its property, you are editing the first element (the only one that has been created already).
so the code should be written like this :
let dynamicList = document.querySelector("#dynamic-list"),
dynamicClass = document.querySelector(".dynamic"),
circle = document.querySelector(".circle");
input.addEventListener("keypress", function(e) {
value = input.value
if (e.key == "Enter") {
const paragraphTest = document.createElement("p"),
dynamicDiv = document.createElement("div"),
circleTest = document.createElement("div");
for (i = 0; i <= dynamicList.children.length; i++) {
dynamicList.insertBefore(dynamicDiv, dynamicClass.nextSibling)
let sibling = dynamicClass.nextSibling;
sibling.classList.add("dynamic")
sibling.appendChild(circleTest)
circleTest.classList.add("circle")
sibling.appendChild(paragraphTest)
paragraphTest.innerHTML = input.value
}
}
})

remove hidden class on X items per click on list

I have a large list of transactions where only 5 items are visible at page load.
I have a button to load the rest by simply removing a "hidden" class. But I do not want to display them all at the button click but only 5 at a time.
I am a bit unsure of how I can do this.
My current script
const cashBackTransactionsWrapper = document.querySelector('.cashback--transactions');
if (cashBackTransactionsWrapper !== null) {
const morePostingsButton = document.querySelector('.cash-back--morepostings');
morePostingsButton.addEventListener('click', function (e) {
e.preventDefault();
const cashbackTableRowHidden = cashBackTransactionsWrapper.querySelectorAll('.flex-table.hidden');
for (var i = 0; cashbackTableRowHidden.length > 0; i++) {
cashbackTableRowHidden[i].classList.remove('hidden');
}
});
}
What I want to achieve is that when the user click the "morepostings" button the next 5 items have their hidden class remove. When the user clicks the button again, the next 5 items have the class removed and so forth.
A pagination-style functionality, if you will.
You have infinite for loop. You should replace your condition with i < 5. Should help :)
const cashBackTransactionsWrapper = document.querySelector('.cashback--transactions');
if (cashBackTransactionsWrapper !== null) {
const morePostingsButton = document.querySelector('.cash-back--morepostings');
morePostingsButton.addEventListener('click', function (e) {
e.preventDefault();
const cashbackTableRowHidden = cashBackTransactionsWrapper.querySelectorAll('.flex-table.hidden');
for (var i = 0; i < 5; i++) {
cashbackTableRowHidden[i].classList.remove('hidden');
}
});
}

How to add event listener to buttons in a loop

I'm new to javascript and I'm trying to create a menu of buttons. In the menu, I want to add event listeners when I click a button.
My problem is I'm not sure how to implement it, to make it possible to target each button with the specific code that button need to run.
I have a button that needs to turn red when clicked and another that needs to load another site. How is it possible to achieve these things.
At the moment I generate the Buttons from a JSON document and create them in the code you can see below.
EDIT: added id attribute to javascript
function createMenu(jsonObj) {
let menu = jsonObj["menuitems"];
console.log(menu[0]);
let table = document.createElement("table");
for (let i = 0; i < menu.length; i++) {
let tableSection = document.createElement("tr");
let tableItem = document.createElement("td");
tableSection.appendChild(tableItem);
let button = document.createElement("BUTTON");
tableItem.appendChild(button);
let text = document.createTextNode(menu[i].item);
button.appendChild(text);
button.classList.add("menuButtons");
table.appendChild(tableSection);
button.setAttribute("id", menu[i].id);
button.addEventListener("click",/*What do i write here*/);
}
document.getElementById("menuDiv").appendChild(table);
}
Standards advice to not declare variable in loop. You can make an attribute (data-horsSujet) and compare the value to know what to do. Like this :
function createMenu(jsonObj) {
const menu = jsonObj["menuitems"];
console.log(menu[0]);
const table = document.createElement("table");
const myfct = function (event) {
const button = event.target;
if (button.getAttribute("data-horsSujet") == 1)
button.style.color = "red";
else
document.location = "google.fr";
}
for (let i = 0, tableSection, tableItem, button, text; i < menu.length; i++) {
tableSection = document.createElement("tr");
tableItem = document.createElement("td");
tableSection.appendChild(tableItem);
button = document.createElement("BUTTON");
tableItem.appendChild(button);
text = document.createTextNode(menu[i].item);
button.appendChild(text);
button.classList.add("menuButtons");
table.appendChild(tableSection);
button.setAttribute("id", menu[i].id);
button.addEventListener("click", myfct);
button.setAttribute("data-horsSujet", i);
}
document.getElementById("menuDiv").appendChild(table);
}

How to restore removed item from array?

I have a users card list, my task is:
Clicking "undo" button: will restore the last card that was deleted (use array)
Question 1: How to make array from cards list I have displayed ?
Question 2: How to restore the last card that was deleted?
(IF 2 cards are removed, "undo" button will to restore card one by one)
Link to codepen here https://codepen.io/MarinaShumeiko/pen/Nbeqew?editors=1010
var root = 'https://jsonplaceholder.typicode.com';
var notificationMessage = "Oops, there are no more user cards to display";
var userIndex = 0;
var undoBtn = $("#button")
var $clearBtn = $("#clear");
var $contentArea = $("#content");
var cardTemplate = '<div class="card" data-id="{id}"><div class="title"><div class="image"></div><div class="name">{name}</div><button onclick="removeUser({postid})" class="close"></button></div><div class="description">{body}{email}</div></div>';
// - Load all the card at once, when screen load
$(function() {
$contentArea.append(renderUser);
});
// Make array from usercards
var $cardDiv = $(".card");
var usersCardArray = $cardDiv.toArray(); // return usersCardArray.length = 0 :(
//remove all card at once
$clearBtn.click(clearUsers);
function clearUsers () {
$contentArea.empty();
userIndex = 0;
}
//remove one card
$('.card .close').on('click', removeUser);
function removeUser(postId) {
$('[data-id="' + postId + '"]').remove();
}
// get user data
function getUser () {
return $.ajax({ url: root + '/posts/1/comments', method: 'GET' });
}
function renderUser() {
getUser().then(function (user) {
for (var i = 0; i = user.length; i++) {
var card = cardTemplate
.replace('{id}', user[userIndex].id)
.replace('{postid}', user[userIndex].id)
.replace('{name}', user[userIndex].name)
.replace('{body}', user[userIndex].body)
.replace('{email}', user[userIndex].email);
$contentArea.append(card);
userIndex++;
}
})
}
Since you don't manipulate any actual data, only the view itself - you can add class .hidden on delete card, and remove this class on undo.
To keep track on deleted users I added array var deletedUsers =[]. Each time you delete a user, add its id to array and hide it from view by adding class hidden.
On undo - pop the user id from deletedUsers, and remove class hidden from this user's card
https://codepen.io/anon/pen/PbXxrB

tags underneath headings disappear when clicked again w/ javascript no idea why

I have pasted the javascript below but also a link to my codepen so you can see exactly what I am talking about.
I would like the heading to be clicked and expose the text below. On another click I would like for the text to go back to hidden. Multiple headings can be opened at the same time. What is happening with my current setup is you can click once to show, click again to hide and then when you click again to show nothing shows, if you keep clicking the text and headings below are eaten/dissapear. I would prefer to do this without jquery. thanks for any help.
http://codepen.io/jrutishauser/pen/YPrrNa
var clickToShow = function () {
if (this.nextElementSibling.className === 'open'){
this.nextElementSibling.remove('open');
} else if (this.nextElementSibling.className != 'open') {
this.nextElementSibling.className = 'open';
}
};
var articleHeadings = document.getElementsByTagName('h3');
for (var index = 0; index < articleHeadings.length; index++){
articleHeadings[index].onclick = clickToShow;
}
var subArticleHeadings = document.getElementsByTagName('h4');
for (var index2 = 0; index2 < subArticleHeadings.length; index2++){
subArticleHeadings[index2].onclick = clickToShow;
}
Change this.nextElementSibling.remove('open') to this.nextElementSibling.className = ''. I believe remove() method removes the element, not the class.
You can do it like this also. This is the correct way of doing it.
var clickToShow = function () {
element=this.nextElementSibling;
if (element.className === 'open'){
element.className=element.className.replace('open','');
} else if (element.className != 'open') {
element.className = 'open';
}
};

Categories

Resources