Highlighting active tab after overriding the active class (jQuery) - javascript

I am having issues highlighting the active tab of a navbar (bootstrap)
The page works like so:
User Adds a product
Once added a new tab will appear with the products name shown
The user can then click on that tab to checkoff checkboxes belonging to that product
Keep adding products and/or deleting products
During step 3 the tab color is updated to match the color of the progress bar within the tab.
My problem is that I want the tab to have a different color when it is selected (active) and then revert back to the progress bar color once another tab is clicked.
Code:
$(document).ready(function () {
$('#new').keypress(function (e) {
var key = e.which;
if (key == 13) {
AddTabFromTemplate($('#newProductName').val());
}
})
$('#btnAddNew').on('click', function () {
AddTabFromTemplate($('#newProductName').val());
});
// Listen for all js-deletetab in the context of #tab-content, even if the tab panels are dynamically generated
$('#tab-content').on('click', '.js-deletetab', function () {
// Find the parent tab-pane's ID and call the Remove Tab function
RemoveTab($(this).parents('.tab-pane').attr('id'));
});
});
function AddTabFromTemplate(newID) {
// Sanitize ID in here is fine
var domID = newID.replace(/ /g, '_');
// Make a copy of the template
$newTab = $('#template').clone();
$newTab.attr('id', domID);
// Insert the new tab page right before our "new" tab.
$newTab.insertBefore('#new');
// Create the tab item, too
var tab = $('<li role="presentation">' + newID + '</li>').insertBefore('#newTab');
tab = tab.find('a');
//Update ProgressBar
ProgressBar($newTab, tab);
}
//Uses the newly created tab to target its progress bar
function ProgressBar( currentTab, liTab){
//Grab all the checkboxes
var checkboxes = currentTab.find('.checkbox');
liTab.css({
'background-color': '#D9534F',// red = #D9534F;
'color': 'white'
});
//Grab the Landing required checkboxes
var landDisp = currentTab.find('.land-display');
var landingPage = currentTab.find('.req');
var landReq = false;
landDisp.css('display', 'none');
//If landing page is required display the rest of the checkboxes
// and updated the landReq bool
landingPage.on('click', function(){
if(landReq === false){
landDisp.toggle();
landReq = true;
}
else if(landReq === true){
landDisp.toggle();
landReq = false;
}
})
checkboxes.on('click', function(){
var emptyValue = 0;
//Checks each checkbox in the tab for checked or not checked
checkboxes.each(function() {
if($(this).is(':checked')){
//If the landing required checkbox is checked update
// the value of the emptyValue for progress bar
if(landReq === false){
emptyValue += 5.3;
}
else if(landReq === true){
emptyValue += 4.4;
}
}
});
//Progressbar update section
if(emptyValue > 30 && emptyValue < 70 ){
currentTab.find('.progress-bar').removeClass('progress-bar-danger');
currentTab.find('.progress-bar').addClass('progress-bar-warning');
liTab.css('background-color', '#F0AD4E');// yellow = #F0AD4E;
}
else if(emptyValue >= 70){
currentTab.find('.progress-bar').removeClass('progress-bar-warning');
currentTab.find('.progress-bar').addClass('progress-bar-success');
liTab.css('background-color', '#5CB85C');// green = #5CB85C;
}
currentTab.find('.progress-bar').css('width', emptyValue + '%').attr('aria-valuenow', emptyValue);
});
}
Codepen
Any help is appreciated.

You can add
li.active a {
background-color: black !important;
}
Here is a working codepen.
The background color for the a tag will be black as long as the li has the active class. Using the !important we overrider the inline-style definition of that a tag.

Related

Closing toggle menu not working properly with JQuery code

I am working on closing toggle menu for mobiles and having a small problem. So what i want is when the toggle menu is active, user to be able to close it by touching somewhere on the screen on his device. I almost got it working, but when closed the basket in the header disappears and the menu doesn't retrieve to a hamburger icon. I am working on Wordpress website, just to notice.
I guess the problem comes from this: aria-expanded="true" , because the default value should be false after the user has closed it.
So my website is:
https://www.ngraveme.com/bg
my JQuery code is:
jQuery(document).ready(function($) {
var $menu = $('.menu');
$('.menu-toggle').click(function() {
$menu.toggle();
});
$(document).mouseup(function(e) {
if (!$menu.is(e.target) // if the target of the click isn't the container...
&&
$menu.has(e.target).length === 0) // ... nor a descendant of the container
{
$menu.hide();
}
});
});
and the original js code written from the theme i am using in wordpress is:
/**
* navigation.js
*
* Handles toggling the navigation menu for small screens.
* Also adds a focus class to parent li's for accessibility.
* Finally adds a class required to reveal the search in the handheld footer bar.
*/
(function() {
// Wait for DOM to be ready.
document.addEventListener('DOMContentLoaded', function() {
var container = document.getElementById('site-navigation');
if (!container) {
return;
}
var button = container.querySelector('button');
if (!button) {
return;
}
var menu = container.querySelector('ul');
// Hide menu toggle button if menu is empty and return early.
if (!menu) {
button.style.display = 'none';
return;
}
button.setAttribute('aria-expanded', 'false');
menu.setAttribute('aria-expanded', 'false');
menu.classList.add('nav-menu');
button.addEventListener('click', function() {
container.classList.toggle('toggled');
var expanded = container.classList.contains('toggled') ? 'true' : 'false';
button.setAttribute('aria-expanded', expanded);
menu.setAttribute('aria-expanded', expanded);
});
// Add class to footer search when clicked.
document.querySelectorAll('.storefront-handheld-footer-bar .search > a').forEach(function(anchor) {
anchor.addEventListener('click', function(event) {
anchor.parentElement.classList.toggle('active');
event.preventDefault();
});
});
// Add focus class to parents of sub-menu anchors.
document.querySelectorAll('.site-header .menu-item > a, .site-header .page_item > a, .site-header-cart a').forEach(function(anchor) {
var li = anchor.parentNode;
anchor.addEventListener('focus', function() {
li.classList.add('focus');
});
anchor.addEventListener('blur', function() {
li.classList.remove('focus');
});
});
// Add an identifying class to dropdowns when on a touch device
// This is required to switch the dropdown hiding method from a negative `left` value to `display: none`.
if (('ontouchstart' in window || navigator.maxTouchPoints) && window.innerWidth > 767) {
document.querySelectorAll('.site-header ul ul, .site-header-cart .widget_shopping_cart').forEach(function(element) {
element.classList.add('sub-menu--is-touch-device');
});
}
});
})();
Try replacing your jQuery code with this:
jQuery(document).ready(function($) {
$(document).mouseup(function(e) {
var $menuContainer = $('.menu');
var $menu = $menu.find('ul');
var $container = $('.site-navigation');
var $button = $container.find('button')
if (!$menuContainer.is(e.target) && $menuContainer.has(e.target).length === 0) {
if ($container.hasClass('toggled')) {
$button.attr('aria-expanded', false);
$menu.attr('aria-expanded', false);
}
}
});
});
It uses the vanilla-js code from the template for hiding/showing the menu, but with jQuery synthax.

How to show all list items again that were previously hidden by jQuery?

I have a search box that filters results and hides them if they don't match the filter:
$('#box_street').keyup(function() {
var valThis = $(this).val().toLowerCase();
if (valThis == "") {
$('#street__list > .list__item').show();
} else {
$('#street__list > .list__item').each(function() {
var text = ($(this).text() + $(this).data("alt")).toLowerCase();
if (text.indexOf(valThis) >= 0) {
$(this).show()
} else {
$(this).hide();
}
});
};
});
Now, I added a function that clear the search box with $('.search__filter').val(''); The problem is, once that runs the items that were previously hidden don't show again. The form input resets ok, but the items are still hidden.
How can I show them all again?
Once the search input is empty, all you have to do is trigger the keyup event, as you already have a condition that shows all the elements
$('#reset_button').on('click', function() {
$('.search__filter').val('');
// reset form ... then
$('#box_street').trigger('keyup');
// or you could do it yourself directly with :
// $('#street__list > .list__item').show();
});

Button is being disabled due to hidden select elements

I have a form with three select options:
Fit
Colour
Size
By default, the 'Fit' dropdown and 'Colour' dropdown are active with a default value selected (e.g. Regular Fit and Blue Colour).
There are three different 'Size' dropdowns, but only one is visible at any time depending on what is selected from the 'Fit' dropdown.
The Button is disabled if an option value="none".
Problem
The Button only becomes active if all three 'Size' dropdowns are altered so that their value is not "none" (this is done by selecting an initial size for Regular, and then selecting Petite and Long from the 'Fit' dropdown). Ideally, I only want the button to take into account the 'Size' dropdown that is active.
Update
Working jsFiddle solution provided by #nagappan below, big thanks.
https://jsfiddle.net/dodgers76/c0dvdwbz/
var currentSelectedVals = {'selector-fit':'','selector-color':'','selector-sizes':''};
var disableComboVals = [
{'selector-fit':'','selector-color':'','selector-sizes':'none'},
{'selector-fit':'petite','selector-color':'','selector-sizes':'10'},
{'selector-fit':'petite','selector-color':'','selector-sizes':'20'},
{'selector-fit':'petite','selector-color':'','selector-sizes':'22'},
{'selector-fit':'petite','selector-color':'','selector-sizes':'24'},
{'selector-fit':'long','selector-color':'','selector-sizes':'22'},
{'selector-fit':'long','selector-color':'','selector-sizes':'24'}
];
function checkDisableCombo() {
return $.grep(disableComboVals, function(vals){
cnt = 0;
$.each(vals, function(key,val) {
console.log('comparing key val '+key+val);
if (val === '' || val === currentSelectedVals[key]) {
console.log('>>matched values');
cnt = cnt + 1;
}
});
if (cnt===3) {
return true;
}
return false;
});
};
$(function(){
var sizeVal = 'none';
$("select.selector-fit").on("change", function(){
//remove active
$("select.selector-sizes.active").removeClass("active");
//check if select class exists. If it does then show it
var subList = $("select.selector-sizes."+$(this).val());
if (subList.length){
//class exists. Show it by adding active class to it
subList.addClass("active");
subList.val(sizeVal);
}
});
$('.selector-sizes').on('change', function() {
sizeVal = $(this).val();
});
});
$(function() {
$('.selector').on('change', function() {
var $sels = $('option.selector-sizes:selected[value="none"]');
var isSizeSelector = jQuery.inArray( "selector-sizes",this.classList);
currentSelectedVals[this.classList[1]] = this.value;
console.log(currentSelectedVals);
var result = checkDisableCombo();
console.log(result);
if ( result.length > 0) {
console.log('disabled false');
$("#Testing").attr("disabled", true);
} else {
$("#Testing").attr("disabled", false);
}
}).change();
});
If we want to disable the button by combination of the drop down selected values. We can have a global variable to track the current selected values from three drop downs. Only we can have array of disbale combos. So whenever user select a value we cross check with disable combos and if it matches we can disable the button. Validate the combo can be done as below. Updated the jsfiddle link. JS FIDDLE UPDATED
function checkDisableCombo() {
return $.grep(disableComboVals, function(vals){
cnt = 0;
$.each(vals, function(key,val) {
console.log('comparing key val '+key+val);
if (val === '' || val === currentSelectedVals[key]) {
console.log('>>matched values');
cnt = cnt + 1;
}
});
if (cnt===3) {
return true;
}
return false;
});

(Javascript) Div toggle and cookies

I want to toggle a div#featuredout using a button .featToggle and I want the browser to remember via cookies whether the div#featuredout should be hidden or shown. If possible, I'd like it to be so that if #featuredout is hidden, .featToggle should have an additional class of "hidden" and if #featuredout is shown, .featToggle should have an additional class of "shown".
I'm very very inexperienced with Javascript so any help would be great.
This is my current code:
$(document).ready(function() {
// When the toggle button is clicked:
$('.featToggle').click(function() {
$('#featuredout').slideToggle(550);
var featuredoutC = $.cookie('featuredout');
if (featuredoutC == null) {$.cookie('featuredout', 'expanded');};
else if (featuredoutC == 'expanded') {$.cookie('featuredout', 'collapsed');};
});
});
// COOKIES
// state
var featuredout = $.cookie('featuredout');
// Set the user's selection for the left column
if (featuredout == 'collapsed') {
$('#featuredout').css("display","none");
$.cookie('featuredout', 'collapsed');
};
});
Something along the lines of this should work
$(function() {
$('.featToggle').click( function() {
$('#featuredout').slideToggle(550);
$.cookie('featuredout',$('#featuredout').is(':visible'););
});
var vis = $.cookie('featuredout');
if(vis) {
$('.featToggle').removeClass('hidden').addClass('shown');
} else {
$('#featuredout').hide();
$('.featToggle').removeClass('shown').addClass('hidden');
}
});

how to select all class except the clicked element in JQuery?

I have a website developed on Drupal. I use a module called collapsiblock (it is basicly a JQuery plugin) to achieve accordion like effect. It is working fine with me (although it is in Beta). But I want to modify it so that when the user clicks on one item of the accordion the other items will collapsed.
In its current stats, it is working in a way that when the user click on one item, it will check if the item is already collapsed or expanded and it will make the item the opposite. That means if the user clicks on one item it will expand and if he/she clicks on another item it will also expand, but it will not collapse the previously clicked item.
You can see the code below. I know where should I add the code to collapse and how to collapse and expand. My question is: How do I select all the items that have the class '.collapsiblock' except the one that the user has clicked??
Note: the item that has the class '.collapsiblockCollapsed' get collapsed and if this class is removed from the item it get expanded.
// $Id: collapsiblock.js,v 1.6 2010/08/18 19:17:37 gagarine Exp $
Drupal.Collapsiblock = Drupal.Collapsiblock || {};
Drupal.behaviors.collapsiblock = function (context) {
var cookieData = Drupal.Collapsiblock.getCookieData();
var slidetype = Drupal.settings.collapsiblock.slide_type;
var defaultState = Drupal.settings.collapsiblock.default_state;
var slidespeed = parseInt(Drupal.settings.collapsiblock.slide_speed);
$('div.block:not(.collapsiblock-processed)', context).addClass('collapsiblock-processed').each(function () {
var id = this.id;
var titleElt = $(':header:first', this).not($('.content :header',this));
if (titleElt.size()) {
titleElt = titleElt[0];
// Status values: 1 = not collapsible, 2 = collapsible and expanded, 3 = collapsible and collapsed, 4 = always collapsed
var stat = Drupal.settings.collapsiblock.blocks[this.id] ? Drupal.settings.collapsiblock.blocks[this.id] : defaultState;
if (stat == 1) {
return;
}
titleElt.target = $(this).find('div.content');
$(titleElt)
.addClass('collapsiblock')
.click(function () {
var st = Drupal.Collapsiblock.getCookieData();
if ($(this).is('.collapsiblockCollapsed')) {
$(this).removeClass('collapsiblockCollapsed');
if (slidetype == 1) {
$(this.target).slideDown(slidespeed);
}
else {
$(this.target).animate({height:'show', opacity:'show'}, slidespeed);
}
// Don't save cookie data if the block is always collapsed.
if (stat != 4) {
st[id] = 1;
}
}
else {
$(this).addClass('collapsiblockCollapsed');
if (slidetype == 1) {
$(this.target).slideUp(slidespeed);
}
else {
$(this.target).animate({height:'hide', opacity:'hide'}, slidespeed);
}
// Don't save cookie data if the block is always collapsed.
if (stat != 4) {
st[id] = 0;
}
}
// Stringify the object in JSON format for saving in the cookie.
var cookieString = '{ ';
var cookieParts = [];
$.each(st, function (id, setting) {
cookieParts[cookieParts.length] = ' "' + id + '": ' + setting;
});
cookieString += cookieParts.join(', ') + ' }';
$.cookie('collapsiblock', cookieString, {path: Drupal.settings.basePath});
});
// Leave active blocks uncollapsed. If the block is expanded, do nothing.
if (stat == 4 || (cookieData[id] == 0 || (stat == 3 && cookieData[id] == undefined)) && !$(this).find('a.active').size()) {
$(titleElt).addClass('collapsiblockCollapsed');
$(titleElt.target).hide();
}
}
});
};
Drupal.Collapsiblock.getCookieData = function () {
var cookieString = $.cookie('collapsiblock');
return cookieString ? Drupal.parseJson(cookieString) : {};
};
UPDATE:
Problem has been solved by adding the following code:
$('.collapsiblock').not(this).each(function(){
$(this).addClass('collapsiblockCollapsed');
$(this.target).animate({height:'hide', opacity:'hide'}, slidespeed);
});
just above the following line:
$(this).removeClass('collapsiblockCollapsed');
Use the not selector.
Example:
$('.collapsiblock').click(function(){
$('.collapsiblock').not(this).each(function(){
$(this).slideUp();
});
$(this).slideDown();
})
Try this,This is a better way because if you use each function it will load and in the future when you have more than a thousand div it will take a long time to slide up and slide down.
Example:
$('.collapsiblock').click(function(){
$('.collapsiblock').not(this).slideUp();
$(this).slideDown();
});
You could keep track of which element has already been clicked with your own jquery click handler and jquery's data(...) function. Then filter iterating your .collapsiblock items with jquery's filter (...) function to include the items you need.

Categories

Resources