remove hidden class on X items per click on list - javascript

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

Related

Having errors with on click function to show/hide content

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

Open only one submenu when clicked on the parent in Vanilla JS

I'm trying to build a menu with a submenu. I used forEach to loop over the menu items and inside of it I used a for loop to show the submenu for that specific menu. However when I click on the parent menu all the submenus appear (Example 1 below)
I'm fairly new to Javascript. Is there a way to fix this? or maybe a better way to do it?.
Thanks!
Example 1
Here is the JS code:
const menuLink = document.querySelectorAll(".nav-link-mobile");
const subMenu = document.querySelectorAll(".mobile-submenu");
menuLink.forEach(function (element) {
element.addEventListener("click", () => {
for (let i = 0; i < subMenu.length; i++) {
subMenu[i].classList.toggle("mobile-submenu-visible");
console.log(subMenu.length);
}
});
});
Without your HTML, or an reproductible exemple it is difficult to says.
But try adding the index.
menuLink.forEach(function (element, index) {
element[index].addEventListener("click", () => {
for (let i = 0; i < subMenu.length; i++) {
subMenu[i].classList.toggle("mobile-submenu-visible");
console.log(subMenu.length);
}
});
If it is not that I will need more from your code.
You have a click Event on the menuLink, that when clicked (called) loops over every subMenu item. You want to put the click Event directly on the subMenu. I would do something like:
let sub;
for(let m of menuLink){
sub = m.querySelectorAll('.mobile-submenu');
for(let s of sub){
s.onclick = function(){
this.classList.toggle('mobile-submenu-visible');
}
}
}

Javascript remove child on click based on class

I'm making a basic list using vanilla javascript. I am able to add items, and change their class when they are clicked. Now, I want the items that have been selected (so their class has been changed) to be removed when they are clicked. At the bottom of the code, I am trying to loop through the list, then if the element in the list has the selected class, an event listener will remove the element when clicked, but this isn't working for me. Any ideas on what I'm doing wrong? (live demo: http://codepen.io/nicolaswilmot/pen/oXLgyq)
Here is the code:
var list = document.getElementById("theList"); // Get the list
// Add new item to top of list
function addItem(e) {
var userTxt = document.getElementById("userInput"); // Get user text
var newItem = document.createElement("li"); // Create new list item
var itemTxt = document.createTextNode(userTxt.value); // Get the text for item
newItem.appendChild(itemTxt); // Add text to list item
list.insertBefore(newItem, list.firstChild); // Put new item at top of list
newItem.className = 'defaultItem'; // Set default class for li
document.getElementById("userInput").value = ''; // Clear the input box
e.preventDefault(); // Prevent page from reloading when page is submitted
// Changes list item class
function changeClass () {
newItem.className = 'selectedItem';
}
// Initialize array for list items
listArray = [];
// Loop through list, add items to array, update class and counter
// when items are clicked
for (var i=0; i<list.children.length; i++) {
listArray.push(newItem);
listArray[i].addEventListener("click",changeClass);
listArray[i].addEventListener("click",countStuff);
}
}
var docForm = document.getElementById("theForm"); // Get the form element
docForm.addEventListener('submit',addItem,false); // Call addItem function when form is submitted
docForm.addEventListener('submit',countStuff,false); //Call counter when form submitted
// Function for the list item counter
function countStuff() {
// Get div container for counter
var itemCount = document.getElementById("counter");
// Get all list items that have not been selected (default class)
var unselectedItems = document.querySelectorAll('li.defaultItem');
//If more than one item, display plural "items"
if (unselectedItems.length > 1) {
itemCount.innerHTML = 'You still need '+unselectedItems.length+' items!';
} else if (unselectedItems.length == 0) {
itemCount.innerHTML = 'You have all items!';
} else {
itemCount.innerHTML = 'You still need '+unselectedItems.length+' item!';
}
}
// Loop through the list
for (var i=0; i<list.children.length; i++) {
// Remove items that are in selected state
if (list.childNodes[i].className='selectedItem') {
list.childNodes[i].addEventListener('click',function () {
list.removeChild([i])},false);
}
}
The placement of your code where you are trying to remove the element once it has the selectedItem class does not make sense, because that code will only run once on page load when the page has no items in the list. Instead, in the same function where you add the selectedItem class, you can bind an event listener to that DOM element that removes it from the list on the next click. http://codepen.io/anon/pen/vOKEzz
function changeClass () {
newItem.className = 'selectedItem';
//Remove it on click!
newItem.addEventListener('click',function () {
list.removeChild(newItem)
}, false);
}

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

disable all the elements in html

How can we disable all the elements in html through javascript.The easiest way...
I suggest to do it the "Lightbox"-style way.
Add an absolute positioned, transparent, full screen div Layer above the Page.
This way, the user can't even click on a Link.
To give the user a visual feedback that the page is disabled,
you can make the div e. g. 50% transparent black.
BTW, here is also a jQuery Plugin that uses a similar technique.
The easiest way is to put all form elements you want to disable inside a <fieldset> and then disable the fieldset itself.
An example: http://jsfiddle.net/xdkf9b8j/1/
If you don't want the border around the fieldset, remove it per css.
Try this,
function disableForm(theform) {
if (document.all || document.getElementById) {
for (i = 0; i < theform.length; i++) {
var formElement = theform.elements[i];
if (true) {
formElement.disabled = true;
}
}
}
}
Or else you can try this too, as RaYell said
function disableForm() {
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
inputs[i].disabled = true;
}
var selects = document.getElementsByTagName("select");
for (var i = 0; i < selects.length; i++) {
selects[i].disabled = true;
}
var textareas = document.getElementsByTagName("textarea");
for (var i = 0; i < textareas.length; i++) {
textareas[i].disabled = true;
}
var buttons = document.getElementsByTagName("button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].disabled = true;
}
}
To disable the whole page you can find some info here,
I don't know why you would need that but this will work:
// this will disable all input elements
var elems = document.getElementsByTagName('input');
var len = elems.length;
for (var i = 0; i < len; i++) {
elems[i].disabled = true;
}
All the form elements (inputs, selects, textareas) within a form, are accesible through the form.elements HTMLCollection, you can iterate the collection disabling each element:
function disableForm(form) {
var length = form.elements.length,
i;
for (i=0; i < length; i++) {
form.elements[i].disabled = true;
}
}
Usage examples:
disableForm(document.forms[0]);
disableForm(document.getElementById('formId'));
Once i had to create a tutorial for my website. I needed to disable all interactions on a page excluding some elements. To do so i used this method:
First make sure to remove all events bindings from your page elements. You can do this by using:
$('*').unbind();
Next disable all links on your page:
$('a').each(function(){$(this).click(function(){return false;})});
and disable all inputs:
$('input').attr('disabled', true);
The code needs to be executed at the end of your document. BTW you may exclude some elements within jquery selector to keep them active.
To lock:
var controls = document.querySelectorAll("button, input, select, textarea");
for (var c of controls) {
c.disabled = true;
}
To unlock:
var controls = document.querySelectorAll("button, input, select, textarea");
for (var c of controls) {
c.disabled = false;
}
That simple.
Just and without crutches!
/**
* Enable/disable all form controlls
* #param status Status: true - form active, false - form unactive
*/
HTMLFormElement.prototype.setStatus = function (status) {
for (var i in this.elements) {
this.elements[i].disabled = !status;
}
};
// Example:
var my_form = document.getElementById('my_form_with_many_inputs');
my_form.setStatus(false); // Disable all inputs in form
my_form.setStatus(true); // Enable all inputs in form
Depending what result you need you could also do
`document.getElementById('main_form').style.display = 'none';`
Where main_form is the id of your form. You can use the same technique to hide a div containing whatever elements you want to disable.
The best way is to add a div with highest z-index having width:100% and height:100%.It will cover your entire page and make everything not clickable means disabled virtually.It is best,because it will not use any loop and any complex code.

Categories

Resources