I have the following landing page
When the page loads I want the left page to be active as shown unfortunately for now when the page loads both the left menu and the right menu are active.If I click on the right menu it does not work.
Hosted site
https://leskoy.bonusgigs.com/
window.onload = function() {
document.getElementById('scarves').className = '';
document.getElementsByClassName('rightlinks')[0].className = 'active'
};
function openLeftMenu(menu) {
if (menu === 'scarves') {
document.getElementById('scarves').className = '';
document.getElementById('stockists').className = 'content';
document.getElementById('scarvesBtn').className = 'active';
document.getElementById('stockistsBtn').className = '';
}
if (menu === 'stockists') {
document.getElementById('stockists').className = '';
document.getElementById('scarves').className = 'content';
document.getElementById('stockistsBtn').className = 'active';
document.getElementById('scarvesBtn').className = '';
}
}
window.onload = function() {
document.getElementById('why').className = '';
document.getElementsByClassName('tablinks')[0].className = 'active'
};
function openMenu(menu) {
if (menu === 'why') {
document.getElementById('why').className = '';
document.getElementById('process').className = 'content';
document.getElementById('whyBtn').className = 'active';
document.getElementById('processBtn').className = '';
}
if (menu === 'process') {
document.getElementById('process').className = '';
document.getElementById('why').className = 'content';
document.getElementById('processBtn').className = 'active';
document.getElementById('whyBtn').className = '';
}
if (menu === 'connect') {
document.getElementById('connect').className = '';
document.getElementById('process').className = 'content';
document.getElementById('connectBtn').className = 'active';
document.getElementById('whyBtn').className = '';
}
if (menu === 'faq') {
document.getElementById('faq').className = '';
document.getElementById('process').className = 'content';
document.getElementById('faqBtn').className = 'active';
document.getElementById('whyBtn').className = '';
}
}
<div class="leftpane">
<nav style="margin-top: 30px;" id="menu">
<a class="tablinks " onclick="openMenu('why')" id="whyBtn">
<h2 class="cooler">why<span class="arrow"></span></h2>
</a>
<a class="tablinks" onclick="openMenu('process')" id="processBtn">
<h2 class="cooler">process<span class="arrow"></span></h2>
</a>
</nav>
</div>
<div class="middlepane">
<div class="content" id="why"></div>
<div class="content" id="process"></div>
<div class="content" id="scarves"></div>
<div class="content" id="stockists"></div>
</div>
<div class="rightpane">
<div style="margin-top: 60%;">
<nov id="menu">
<a class="rightlinks" onclick="openLeftMenu('scarves')" id="scarvesBtn">
<h2 class="drool">scarves<span class="arrow"></span></h2>
</a>
<a class="rightlinks" onclick="openLeftMenu('stockists')" id="stockistsBtn">
<h2 class="drool">stockists<span class="arrow"></span></h2>
</a>
</nov>
</div>
</div>
Here is how to do more than one thing in the onload.
Also note how I cache the elements and address the first of the class using querySelector
window.addEventListener("DOMContentLoaded", function() {
const scarves = document.getElementById('scarves');
const scarvesBtn = document.getElementById('scarvesBtn');
const stockists = document.getElementById('stockists');
const stockistsBtn = document.getElementById('stockistsBtn');
const why = document.getElementById('why');
const rightlinks = document.querySelector('.rightlinks');
const tablinks = document.querySelector('.tablinks')
const openLeftMenu = menu => {
scarves.classList.toggle("content", menu === 'stockists')
scarvesBtn.classList.toggle("active", menu === 'scarves')
stockists.classList.toggle("content", menu === 'scarves')
.classList.toggle("active", menu === 'stockists')
}
// init
scarves.classList.remove("active");
why.classList.remove("active");
rightlinks.classList.add("active");
tablinks.classList.add("active");
});
Related
I have a doropdown menu that should work when used/in view.
I would like to have a function that works only when the dropdown is used.
So Ideally navigation with dropdown and nav without.
the following fuctions will be added if dropdown exists.
The Click event doesn't seems to fire at all.
My assumption is that
const navLinks = dropDownBlock[i].querySelectorAll(".nav-items > li");
is't correct! or is not fired
I wan't to use as much as possible es6, and I wan't to make sure everything is reusable and works only when in view.
Demo here:
const dropDownBlock = document.querySelectorAll(".has-nav-panel");
let result = true;
for (let i = 0; i < dropDownBlock.length; i++) {
if (dropDownBlock[i] <= 0) {
result = false;
break;
}
const navLinks = dropDownBlock[i].querySelectorAll(".nav-items > li");
const dropdownCta = dropDownBlock[i].querySelector(".nav-panel-cta");
const dropdownPanel = dropDownBlock[i].querySelector(".nav-panel");
//-------------------------------------
//Doesn it have dropdown
//-------------------------------------
Array.prototype.forEach.call(navLinks, function (el, i) {
let currentNavLink = navLinks[i];
currentNavLink.addEventListener("click", function () {
console.log('click');
megaNavClickAndTouchHandler(navLinks, currentNavLink);
});
megaNavResetOnBreakPoint(navLinks, currentNavLink, mediaQuery);
});
function megaNavResetOnBreakPoint(elements, currentElement, mqNav) {
if (matchMedia) {
let navigationBar = currentElement.closest(".header");
let navigationItems = currentElement.closest(".nav-wrap");
mqNav.addListener(function () {
if (mqNav.matches) {
document.querySelectorAll("body")[0].classList.remove("is-no-scroll");
navigationBar.classList.remove("is-active");
navigationItems.classList.remove("is-active");
//navigationBar.querySelectorAll(".burger")[0].classList.remove("is-active");
megaNavClosePanels(elements);
} else {
megaNavClosePanels(elements);
}
});
}
}
function megaNavClickAndTouchHandler(elements, currentElement) {
let isSubNavLink = currentElement.classList.contains("has-nav-panel");
let isSubNavLinkActive = currentElement.classList.contains("is-active");
let navBarContainer = currentElement.closest(".header");
if (!isSubNavLink) {
window.location = currentElement.firstElementChild.getAttribute("href");
} else if (isSubNavLink && !isSubNavLinkActive) {
megaNavClosePanels(elements);
currentElement.classList.add("is-active");
dropdownCta.setAttribute("aria-expanded", true);
dropdownPanel.ariaHidden = "false";
} else {
megaNavClosePanels(elements);
}
}
function megaNavClosePanels(elements) {
for (let j = 0; j < elements.length; j++) {
if (elements[j].classList.contains("has-nav-panel")) {
elements[j].classList.remove("is-active");
dropdownCta.setAttribute("aria-expanded", false);
dropdownPanel.ariaHidden = "true";
}
}
}
//-------------------------------------
// end dropdown functions
//-------------------------------------
}
<header role="banner" class="header">
<div class="container-fluid g-0 bg-black">
<nav id="main-navigation" class="navigation">
<div class="container has-px-0 has-px-md-4">
<div class="nav-wrap" aria-label="main navigation">
<ul class="nav-items list-unstyled">
<li class="is-d-lg-flex active"><a class="nav-link" href="#">nav item</a></li>
<li class="is-d-lg-flex "><a class="nav-link" href="#">nav item</a></li>
<li class="is-d-lg-flex"><a class="nav-link" href="#">nav item</a></li>
<li class="has-nav-panel is-d-lg-flex is-align-center">
<button role="button" aria-expanded="false" class="nav-panel-cta has-pb-3 has-pt-3 has-px-4 has-p-lg-0"><span class="has-mr-2">Dropdown</span></button>
<div class="nav-panel" aria-hidden="true">
<div class="row no-gutters">
<div class="col-md-12">
<ul class="list-unstyled has-pl-3 has-pl-lg-0">
<li>nav item</li>
<li>nav item</li>
</ul>
</div>
</div>
</div>
</li>
</ul>
</div>
</div>
</nav>
</div>
</header>
your html structure
<ul class="nav-items list-unstyled">
<li class="has-nav-panel is-d-lg-flex is-align-center">
but your script select the child then the parent
const dropDownBlock = document.querySelectorAll(".has-nav-panel");
.....
const navLinks = dropDownBlock[i].querySelectorAll(".nav-items > li");
I think you don't need to loop and here fix, replace
const dropDownBlock = document.querySelectorAll(".has-nav-panel");
let result = true;
for (let i = 0; i < dropDownBlock.length; i++) {
if (dropDownBlock[i] <= 0) {
result = false;
break;
}
const navLinks = dropDownBlock[i].querySelectorAll(".nav-items > li");
const dropdownCta = dropDownBlock[i].querySelector(".nav-panel-cta");
const dropdownPanel = dropDownBlock[i].querySelector(".nav-panel");
with
let result = true;
dropDown();
function dropDown() {
let dropDownBlock = document.querySelectorAll(".nav-items")
const navLinks = dropDownBlock[0].querySelectorAll(".has-nav-panel");
if (navLinks .length <= 0) {
result = false;
return;
}
const dropdownCta = dropDownBlock[0].querySelector(".nav-panel-cta");
const dropdownPanel = dropDownBlock[0].querySelector(".nav-panel");
In my electron app I want to toggle between different screens, thus I need to use block and none displays.
I have a side navbar which contain the anchor tags, whenever I click one of those I want my screen to block all the other screens and display the one which was clicked.
Required Code Below
Side NavBar -not attaching the css for it
<div class="sidebar">
Home
Tasks
TimeTable
Quick notes
Expenses
</div>
Different Displays
<div id="home" class="screen" style="display: none">
<h1 class="centertitle">Home</h1>
</div>
<div id="tasks" class="screen" style="display: none">
<h1 class="centertitle">Tasks</h1>
</div>
Script
<script>
function showtasks() {
let task = document.getElementById("tasks");
let taskbtn = document.getElementById("taskbtn");
let allnav = document.getElementsByClassName("nava");
let allscreens = document.getElementsByClassName("screen");
allscreens.style.display = "none";
task.style.display = "block";
allnav.className = "";
taskbtn.className = "active";
}
function showhome() {
let home = document.getElementById("home");
let homebtn = document.getElementById("homebtn");
let allnav = document.getElementsByClassName("nava");
let allscreens = document.getElementsByClassName("screen");
allscreens.style.display = "none";
home.style.display = "block";
allnav.className = "";
homebtn.className = "active";
}
</script>
The problem here is the allscreens variable.
getElementsByClassName returns an array of elements with the given class name. So in order to set them all to display: none, you will need to loop through the elements.
let allscreens = document.getElementsByClassName("screen");
for (var i = 0; i < allscreens.length; i++) {
allscreens[i].style.display = "none";
}
function showtasks() {
let task = document.getElementById("tasks");
let taskbtn = document.getElementById("taskbtn");
let allnav = document.getElementsByClassName("nava");
let allscreens = document.getElementsByClassName("screen");
for (var i = 0; i < allscreens.length; i++ ) {
allscreens[i].style.display = "none";
}
task.style.display = "block";
allnav.className = "";
taskbtn.className = "active";
}
function showhome() {
let home = document.getElementById("home");
let homebtn = document.getElementById("homebtn");
let allnav = document.getElementsByClassName("nava");
let allscreens = document.getElementsByClassName("screen");
for (var i = 0; i < allscreens.length; i++ ) {
allscreens[i].style.display = "none";
}
home.style.display = "block";
allnav.className = "";
homebtn.className = "active";
}
<div class="sidebar">
Home
Tasks
TimeTable
Quick notes
Expenses
</div>
<div id="home" class="screen" style="display: none">
<h1 class="centertitle">Home</h1>
</div>
<div id="tasks" class="screen" style="display: none">
<h1 class="centertitle">Tasks</h1>
</div>
I'm creating something like GMAIL functionality with JavaScript ES5 ( I use only const and let, that's it, rest ES5).
So I manage to create the list functionality, all works except that when I select the items and move them to a different list, they lose any functionality, and I can't do anything with them.
I believe I need to use querySelectorAll to get all the lists, but that doesn't work. Not sure what should I do here.
I think I need to select all the lists, and then loop them to add interactivity.
CodePen: https://codepen.io/Aurelian/pen/dJryrX?editors=1010
JS:
window.onload = function() {
//////////////////////////////////
// VARIABLES
//////////////////////////////////
// Form
const form = document.querySelector('#registrar');
const input = form.querySelector('input');
// Lists
const partyList = document.querySelector('.party-lists');
const partyInvitedList = document.querySelector('#list-invited')
const partyGoingList = document.querySelector('#list-going');
const partyNotSure = document.querySelector('#list-not-sure');
const partyNotGoing = document.querySelector('#list-not-going');
// List Options
const listOptions = document.querySelector('.list-options');
const btnMoveToGoing = document.querySelector('.btnMoveGoing');
const btnMoveToNotSure = document.querySelector('.btnMoveNotSure');
const btnMoveToNotGoing = document.querySelector('.btnMoveNotGoing');
const btnDeleteSelected = document.querySelector('.btnDeleteSelected');
//////////////////////////////////
// FUNCTIONS
//////////////////////////////////
function createLI(text) {
const li = document.createElement('li');
const span = document.createElement('span');
span.textContent = text;
li.appendChild(span);
const label = document.createElement('label');
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
label.appendChild(checkbox);
li.appendChild(label);
const editButton = document.createElement('button');
editButton.textContent = 'edit';
li.appendChild(editButton);
const removeButton = document.createElement('button');
removeButton.textContent = 'remove';
li.appendChild(removeButton);
return li;
}
//////////////////////////////////
// EVENT HANDLERS
//////////////////////////////////
form.addEventListener('submit', function(e) {
e.preventDefault();
const text = input.value;
input.value = '';
const li = createLI(text);
partyInvitedList.appendChild(li);
});
partyList.addEventListener('click', function(e) {
if (e.target.tagName === 'BUTTON') {
const button = e.target;
const li = button.parentNode;
const ul = li.parentNode;
if (button.textContent === 'remove') {
ul.removeChild(li);
} else if (button.textContent === 'edit') {
const span = li.firstElementChild;
const input = document.createElement('input');
input.type = 'text';
input.value = span.textContent;
li.insertBefore(input, span);
li.removeChild(span);
button.textContent = 'save';
} else if (button.textContent === 'save') {
const input = li.firstElementChild;
const span = document.createElement('span');
span.textContent = input.value;
li.insertBefore(span, input);
li.removeChild(input);
button.textContent = 'edit';
}
}
});
listOptions.addEventListener('click', function(e) {
partyList.querySelectorAll('*:checked').forEach(function (listItems) {
const button = e.target;
var items = listItems.parentNode.parentNode;
if(button.className === 'btnMoveGoing') {
partyGoingList.appendChild(items);
items.checked = false;
var item = listItems;
item.checked = false;
} else if(button.className === 'btnMoveNotSure'){
partyNotSure.appendChild(items);
var item = listItems;
item.checked = false;
} else if(button.className === 'btnMoveNotGoing'){
partyNotGoing.appendChild(items);
var item = listItems;
item.checked = false;
} else if(button.className === 'btnDeleteSelected'){
listItems.parentNode.parentNode.remove();
var item = listItems;
item.checked = false;
}
});
});
}
HTML:
<div class="top">
<form id="registrar">
<input type="text" name="name" placeholder="Invite Someone">
<button type="submit" name="submit" value="submit">Submit</button>
</form>
<div class="list-options">
<button class="btnMoveGoing">Move to Going</button>
<button class="btnMoveNotSure">Move to Not Sure</button>
<button class="btnMoveNotGoing">Move to Not Going</button>
<button class="btnDeleteSelected">Delete Selected</button>
</div>
</div><!-- /top -->
<div class="col">
<h3>Invited</h3>
<ul id="list-invited" class="party-lists">
</ul>
</div>
<div class="col">
<h3>Going</h3>
<ul id="list-going" class="party-lists">
</ul>
</div>
<div class="col">
<h3>Not Sure</h3>
<ul id="list-not-sure" class="party-lists">
</ul>
</div>
<div class="col">
<h3>Not Going</h3>
<ul id="list-not-going" class="party-lists">
</ul>
</div>
i am new to angular 4 i want to develop a shopping cart functionality with some different render functionality in html. i can't able to find any solution till now.
already tried with jquery append function but it wont work in edit functionality in feature.
Below gif image shows my requirement
if i click any catagory it will directly append to top of the list with selected catagory.
Then if i click another catagory for same person it will apply after i click apply button
component.html
<ul class="selected-friends" id="appendtext">
</ul>
<ul class="list-friends" id="listFriends">
<div *ngFor="let data of result" [attr.id]="'FriendList' + data.id" #item>
<li class="checkedCatagory">
<div class="sf-left">
<h3>{{data.fullName}}</h3>
<span id="appendCatagoryList"></span>
</div>
<div class="sf-right">
<div class="edit-con sf-icon" data-toggle="collapse" [attr.data-target]="'#list' + data.id">
<i class="fa fa-list" aria-hidden="true"></i>
</div>
<div class="del-con sf-icon" [attr.id]="'#list' + data.id" (click)="delete(data.id)">
<i class="fa fa-trash-o" aria-hidden="true"></i>
</div>
</div>
</li>
<!-- Main List started -->
<li class="mainlistname" data-toggle="collapse" [attr.data-target]="'#list' + data.id">
<label class="catagory_list" [attr.for]="data.id"><input type="checkbox" [attr.id]="data.id" [attr.value]="data.id">
{{data.fullName}}</label>
</li>
<ul class="sub-friends-list collapse" [attr.id]="'list'+data.id">
<p class="mainlistname">Assign Category to this participant</p>
<p class="checkedCatagory">Edit or Assign another category to this participant</p>
<li *ngFor="let catagoryDetail of catagoryList">
<label class="catagory_list">
<input type="checkbox" class="catagory_list_checkbox" (click)="resize(data.id, catagoryDetail.id);addToCart(data.id,catagoryDetail.id,data.fullName,catagoryDetail.title)" [value]="catagoryDetail.id" [attr.id]="'catagoryId'+catagoryDetail.id">
<span [attr.id]="'catagoryName'+catagoryDetail.id">{{catagoryDetail.title}}</span>
<span class="pull-right fnt-16">AED</span>
<span class="pull-right fnt-16" id="'fee'+catagoryDetail.id">{{catagoryDetail.fee}}</span>
<!-- <p>18-99 Years Male/Female</p> -->
<p *ngIf="catagoryDetail.gender === 1">{{catagoryDetail.ageMinMale}}-{{catagoryDetail.ageMaxMale}} Years Male</p>
<p *ngIf="catagoryDetail.gender === 2">{{catagoryDetail.ageMinFemale}}-{{catagoryDetail.ageMaxFemale}} Years Female</p>
<p *ngIf="catagoryDetail.gender === 3">{{catagoryDetail.ageMinFemale}}-{{catagoryDetail.ageMaxFemale}} Years Male/Female</p>
</label>
<span class="checkedCatagoryhidden">
<p *ngFor="let catagorySelected of catagoryList" [attr.id]="'catagorySelected'+catagorySelected.id">
{{catagorySelected.title}} :
<span *ngIf="catagorySelected.gender === 1">{{catagorySelected.ageMinMale}}-{{catagorySelected.ageMaxMale}} Years Male</span>
<span *ngIf="catagorySelected.gender === 2">{{catagorySelected.ageMinFemale}}-{{catagorySelected.ageMaxFemale}} Years Female</span>
<span *ngIf="catagorySelected.gender === 3">{{catagorySelected.ageMinFemale}}-{{catagorySelected.ageMaxFemale}} Years Male/Female</span>
<span class="pull-right fnt-16">AED {{catagorySelected.fee}}</span>
</p>
</span>
</li>
<li class="checkedCatagory" class="apply checkedCatagory quantity">
<span class="quantity_catagory">Qty: <span [attr.id]="'sectionquantity'+data.id"></span></span>
<span class="catagory_amount">Total: AED <span [attr.id]="'sectionprize'+data.id"></span></span>
<button class="btnapplyqnty">Apply</button>
</li>
</ul>
</div>
</ul>
component.ts
addToCart(id, catagoryId, fullName, catTitle){
var currentUserObj = <any>{};
var self = this;
var sum;
currentUserObj[id] = {};
currentUserObj[id].participantid = id;
currentUserObj[id].participantName = fullName;
// console.log(fullName)
this.cart.cartItems[id] = {};
if(jQuery("#catagoryId"+catagoryId).is(":checked")) {
currentUserObj[id]['categoryInfo'] = [];
currentUserObj[id]['categoryName'] = [];
currentUserObj[id]['categoryFee'] = [];
var totalPrize = 0;
jQuery('#list'+id).find('.catagory_list input:checked').each(function(){
var currentCategoryId = jQuery(this).val();
var currentCatagoryName = jQuery('.catagory_list input:checked+#catagoryName'+catagoryId).text();
currentUserObj[id]['categoryInfo'].push(currentCategoryId);
currentUserObj[id]['categoryName'].push(jQuery(this).next('').text());
currentUserObj[id]['categoryFee'].push(Number(jQuery(this).next().next().next().text()));
});
sum = currentUserObj[id]['categoryFee'].reduce(this.add, 0);
currentUserObj[id].quantity = currentUserObj[id]['categoryInfo'].length;
this.cart.cartItems[id] = currentUserObj[id];
currentUserObj[id].participantTotalPrize = sum;
console.log('sum',sum)
this.saveCart();
} else {
var currentCategoryId;
currentUserObj[id]['categoryInfo'] = [];
currentUserObj[id]['categoryName'] = [];
currentUserObj[id]['categoryFee'] = [];
jQuery('#list'+id).find('.catagory_list input:checked').each(function(){
currentCategoryId = jQuery(this).val();
currentUserObj[id]['categoryName'].push(jQuery(this).next().text());
currentUserObj[id]['categoryInfo'].push(currentCategoryId);
currentUserObj[id]['categoryFee'].push(Number(jQuery(this).next().next().next().text()));
});
sum = currentUserObj[id]['categoryFee'].reduce(this.add, 0);
currentUserObj[id].participantTotalPrize = sum;
currentUserObj[id].quantity = currentUserObj[id]['categoryInfo'].length;
this.cart.cartItems[id] = currentUserObj[id];
if(currentUserObj[id].quantity === 0) {
console.log("completed delete", this.cart.cartItems[id])
delete self.cart.cartItems[id];
}
this.saveCart();
}
}
add(a, b) {
return a + b;
}
saveCart() {
if (window.localStorage) {
console.log("tfgb",this.cart);
sessionStorage.setItem('cart',JSON.stringify(this.cart));
}
}
resize(id, catagoryId) {
let navObj = this;
var appendSelectedCatagory = document.getElementById('appendtext');
jQuery(appendSelectedCatagory).prepend(jQuery('#FriendList'+id));
if(jQuery("#catagoryId"+catagoryId).is(":checked")) {
this.displaySelectedList(id, catagoryId);
var totalPrize = 0;
navObj.quantity = 0;
jQuery('#list'+id).find('.catagory_list input:checked').each(function(){
var currentCategoryId = jQuery(this).val();
navObj.eventRegistrationService.getEventCatagoriesList(navObj.eventId)
.subscribe((res)=>{
for(let i in res.data){
var catList = res.data[i];
if(catList.id == currentCategoryId){
totalPrize += catList.fee
navObj.quantity += 1;
}
}
jQuery('#sectionprize'+id).html(totalPrize);
jQuery('#sectionquantity'+id).html(navObj.quantity);
})
})
} else {
this.eventChecked -= 1;
var totalPrize = 0;
navObj.quantity = 0;
jQuery('#list'+id).find('.catagory_list input:checked').each(function(){
var currentCategoryId = jQuery(this).val();
navObj.eventRegistrationService.getEventCatagoriesList(navObj.eventId)
.subscribe((res)=>{
for(let i in res.data){
var catList = res.data[i];
if(catList.id == currentCategoryId){
totalPrize += catList.fee
navObj.quantity += 1;
}
}
jQuery('#sectionprize'+id).html(totalPrize)
jQuery('#sectionquantity'+id).html(navObj.quantity)
})
})
this.checkedCatagory.pop(catagoryId);
let checkBoxList = '#appendtext #list'+id;
if(jQuery(checkBoxList+' :checkbox:checked').length == 0){
jQuery('#listFriends').append(jQuery('#FriendList'+id));
jQuery("#FriendList"+id+ " input[type='checkbox']").prop("checked", false);
sessionStorage.removeItem(id);
}
}
}
displaySelectedList(id, catagoryId){
this.eventChecked += 1;
let getselectList = sessionStorage.getItem('selectedFriends');
jQuery('#appendCatagoryList').append(jQuery('#catagorySelected'+catagoryId))
}
delete(id){
jQuery('#listFriends').append(jQuery('#FriendList'+id));
jQuery("#FriendList"+id+ " input[type='checkbox']").prop("checked", false);
console.log('asdasdsa',id);
//this.quantity = 0;
sessionStorage.removeItem(id);
}
Trying to Add and Remove class to click dynamic Buttons, means this button <button class="one"></button> get class dynamically like this: <button class="one text1">text1</button>
So if button one has class .text1 and by click this add class .hide to list item <li class="text1"> like <li class="text1 show">
Same for button two <button class="two"></button> and by click add class <li class="text2 show">
Note: when click button two, then should remove class .show and add new class .hideto button one.
Main HTML:
<div id="main-id">
<button class="one"></button>
<button class="two"></button>
<ul>
<li>
<!--List 1-->
<div class="label">
text1
</div>
</li>
<li>
<!--List 2 is Same-->
<div class="label">
text1
</div>
</li>
<li>
<!--List 3 is different-->
<div class="label">
text2
</div>
</li>
</ul>
</div>
Script:
$('.label a').each(function() {
var $this=$(this);
$this.closest('li').addClass($this.text());
});
// Combine This
$('button').each(function(){
var liInd = 0;
var cl = '';
var txt = '';
var clses = [];
var ind = $('button').index($(this)) + 1;
$('li').each(function(){
if(clses.indexOf($(this).attr('class')) === -1){
clses.push($(this).attr('class'));
liInd = liInd + 1;
}
if(ind === liInd){
cl = $(this).attr('class');
txt = $(this).find('a').text();
return false; //break
}
});
$('button:nth-child(' + ind + ')').addClass(cl);
$('button:nth-child(' + ind + ')').text(txt);
});
See Example on Fiddle
I have tried this by add/remove class by click function, but problem is Buttons get class dynamically from List items, so I'm not able to target button.
Any suggestion for other way to do this by JS/ Jquery?
Here is an alternative solution
$('button').each(function () {
var liInd = 0;
var cl = '';
var txt = '';
var clses = [];
var ind = $('button').index($(this)) + 1;
$('li').each(function () {
if (clses.indexOf($(this).attr('class')) === -1) {
clses.push($(this).attr('class'));
liInd = liInd + 1;
}
if (ind === liInd) {
cl = $(this).attr('class');
txt = $(this).find('a').text();
return false; //break
}
});
if (txt != '') {
$('button:nth-child(' + ind + ')').addClass(cl);
$('button:nth-child(' + ind + ')').text(txt);
}
});
$('button').click(function () {
if ($(this).attr('class')[0] == 'all') {
showAll();
return false; // end this function
}
var allCls = $(this).attr('class').split(' ');
$('li').each(function () {
if (allCls.indexOf($(this).find('a').text()) > -1) {
$(this).closest('li').removeClass('show').addClass('hide');
} else {
$(this).closest('li').removeClass('hide').addClass('show');
}
});
});
function showAll() {
$('li').removeClass('hide').addClass('show');
}
Fiddle: https://jsfiddle.net/taleebanwar/yaLm4euk/13/
DEMO
$('.label a').each(function () {
var $this = $(this);
$this.closest('li').addClass($this.text());
});
// Combine This
$('button').each(function () {
var liInd = 0;
var cl = '';
var txt = '';
var clses = [];
var ind = $('button').index($(this)) + 1;
$('li').each(function () {
if (clses.indexOf($(this).attr('class')) === -1) {
clses.push($(this).attr('class'));
liInd = liInd + 1;
}
if (ind === liInd) {
cl = $(this).attr('class');
txt = $(this).find('a').text();
return false; //break
}
});
$('button:nth-child(' + ind + ')').addClass(cl);
$('button:nth-child(' + ind + ')').text(txt);
});
$(document).on('click', 'button',function(e){
var textClass = $.grep(this.className.split(" "), function(v, i){
return v.indexOf('text') === 0;
}).join();
console.log(textClass);
$('li').removeClass('show').addClass('hide')
$('li').each(function(){
if($(this).hasClass($.trim(textClass))){
$(this).removeClass('hide').addClass('show');
} else {
$(this).removeClass('show').addClass('hide');
}
})
})
.show{display:list-item;}
.hide{display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="main-id">
<button class="one"></button>
<button class="two"></button>
<ul>
<li>
<!--List 1-->
<div class="label">
text1
</div>
</li>
<li>
<!--List 2 is Same-->
<div class="label">
text1
</div>
</li>
<li>
<!--List 3 is different-->
<div class="label">
text2
</div>
</li>
</ul>
</div>