How to prevent addClass and removeClass repetition - javascript

I'm adding active class to the buttons, and also i'm adding list/grid class to the cards-wrapper based on the button clicked.
Below is the working code. is there a way to write less code to achieve the same output?
$('.buttons button').click(function(e) {
e.preventDefault();
$('button').removeClass('active');
$(this).addClass('active');
if ($(this).hasClass('list')) {
$('.cards-wrapper').removeClass('grid').addClass('list');
}
else if($(this).hasClass('grid')) {
$('.cards-wrapper').removeClass('list').addClass('grid');
}
});
<div class="buttons">
<button class="grid">Grid</button>
<button class="list active">List</button>
</div>
<div class="cards-wrapper list">
<div>Sample Content</div>
</div>

You can use the jQuery toggleClass method. As the name suggests, this method toggles the given classes for all the elements in the selection.
You can reduce your if/else logic to just one if statement by checking whether the button that was clicked on is not active. Once you have established that the button is not active, you can then just toggle the classes for both of the buttons and for the content wrapper div.
$('.buttons button').click(function(e) {
e.preventDefault();
if (!$(this).hasClass('active')) {
$('button').toggleClass('active');
$('.cards-wrapper').toggleClass('grid list');
}
});
.active {
color: green;
}
.list {
color: red;
}
.grid {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="buttons">
<button>Grid</button>
<button class="active">List</button>
</div>
<div class="cards-wrapper list">
<div>Sample Content</div>
</div>
Using the toggleClass method in this way will break if you add more buttons, though, so take care with it.

There's not much you can do there as you are having two action buttons, if you can make it into a single one, then you can use jQuery's .toggleClass() method here. Hence, you don't have to check for classes using .hasClass() every time.
$('.buttons button').click(function(e) {
//some of your code here
$('.cards-wrapper').toggleClass('grid list');
});

Try using ternary operator not toggleClass() because it will cost bug.
$('.buttons button').click(function(e) {
e.preventDefault();
$('button').removeClass('active');
$(this).addClass('active');
$(this).hasClass('list') ? $('.cards-wrapper').removeClass('grid').addClass('list') : '';
$(this).hasClass('grid') ? $('.cards-wrapper').removeClass('list').addClass('grid') : '';
});
.active{
color:green !important;
}
.list{
color:red;
}
.grid{
color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="buttons">
<button class="grid">Grid</button>
<button class="list active">List</button>
</div>
<div class="cards-wrapper list">
<div>Sample Content</div>
</div>

Try with toggleClass() function of jquery
In your answer addClass() and removeClass() .its right.
But better use with toggleClass().because toggle function to check the class name already present or not.if is it present to remove the class name ,is not add the class.
Its handle with one or more function .See the jquery documentation of
toggleClass()
$('.buttons button').click(function(e) {
e.preventDefault();
$('button').toggleClass('active');
if($(this).hasClass('list')){
$('.cards-wrapper').toggleClass('grid list');
}
else if($(this).hasClass('grid')) {
$('.cards-wrapper').toggleClass('list grid');
}
});
.active{
color:green !important;
}
.list{
color:red;
}
.grid{
color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="buttons">
<button class="grid">Grid</button>
<button class="list active">List</button>
</div>
<div class="cards-wrapper list">
<div>Sample Content</div>
</div>

Related

how to remove the class on clicking a button and adding new class [duplicate]

This question already has answers here:
Easiest way to toggle 2 classes in jQuery
(7 answers)
Closed 1 year ago.
suppose there is a div with class "box" on clicking the button with class "button" I want to remove the class "box" from the div and add a absolutely new class "active" to the div. what will be the jQuery code of the following?
html
<div class="box">
<button class="button">button</button>
</div>
and also how should I add the new class in CSS ? like normally we add.
You can use removeClass method to remove class and use addClass method to add class using jquery.
You can also chain method as:
box.removeClass("box").addClass("active");
const box = $(".box");
$(".button").on("click", function() {
box.removeClass("box");
box.addClass("active");
})
.box {
background-color: red;
}
.active {
background-color: yellowgreen;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box">
<button class="button">button</button>
</div>
Perhaps the easiest way is to use the classList.replace method which you can use with both jQuery, and vanilla JS.
jQuery.
$('.button').click(function () {
const parent = this.parentNode;
parent.classList.replace('box', 'active');
});
.active { background: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box">
<button class="button">button</button>
</div>
Vanilla JS.
const button = document.querySelector('button');
button.addEventListener('click', handleClick, false);
function handleClick() {
const parent = this.parentNode;
parent.classList.replace('box', 'active');
}
.active { background: red; }
<div class="box">
<button class="button">button</button>
</div>
The simplest jQuery technique is probably with toggle:
$('.button').click(function() {
$(this).parent().toggleClass('box active');
});
.box {
background: #ddd;
}
.active {
background: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box">
<button class="button">button</button>
</div>

jQuery ToggleClass on multiple buttons

I am trying to toggle visibility of elements with jQuery. The page should load with all elements active. Then, when you click on one of 3 filter buttons, it should hide the elements that don't match.
I can get it to work with addClass and removeClass, but I want to be able to toggle the elements on and off when you click each button. This is where it falls apart. With toggleClass, it works on the first click, but when I try to toggle the buttons, the classes get all mixed up.
Here is a working fiddle using removeClass (no toggling):
$(".map-filters .heart").click(function() {
$('.blue-marker').addClass('d-none');
$('.green-marker').addClass('d-none');
$('.red-marker').removeClass('d-none');
});
And here is a non-working fiddle where I attempt to toggle the classes –– once you click around a bit, it gets mixed up:
$(".map-filters .heart").click(function() {
$('.blue-marker').addClass('d-none');
$('.green-marker').addClass('d-none');
$('.red-marker').toggleClass('d-none');
});
What am I doing wrong?
Thanks!
1.You have set the default to active to all of them.
2.You have to do make the decision based on the active not active of the button with hasClass()
You don't need code redundancy. You can simplify it by giving each button an id.
$(".map-filters .filter").click(function() {
$('.active').not(this).removeClass('active');
$(this).toggleClass('active');
if ($(this).hasClass('active')){
var color = $(this).attr('id');
$("#map").children().addClass('d-none');
$("." + color + "-marker").toggleClass('d-none');
}
else {
$("#map").children().removeClass('d-none');
}
});
.d-none {
visibility:hidden!important
}
#map {
border:1px solid #000;
padding:20px;
}
#map > div {
width:30px;
height:30px;
display:inline-block;
margin:10px;
}
.map-filters {
margin-top:50px;
}
.map-filters button {
opacity:0.5;
}
.map-filters button.active {
opacity:1;
}
.heart,
.red-marker {background:red;}
.heart-pvl,
.green-marker {background:green;}
.pvl,
.blue-marker {background:blue;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="map">
<div class="blue-marker"></div>
<div class="red-marker"></div>
<div class="red-marker"></div>
<div class="green-marker"></div>
<div class="blue-marker"></div>
<div class="green-marker"></div>
</div>
<div class="map-filters">
<button type="button" class="filter heart" id="red">Heart Locations</button>
<button type="button" class="filter heart-pvl" id="green">Heart & PVL Locations</button>
<button type="button" class="filter pvl" id="blue">PVL Locations</button>
</div>

jQuery Each function class toggling [duplicate]

This question already has answers here:
toggleClass and remove class from all other elements
(6 answers)
Closed 3 years ago.
I have to remove a class for all elements of each() function.
Right now when I click on a .btn element it adds "selected" class to it, again click on .btn it removes that "selected" class.
But when I click other .btn element it should remove "selected" class from previous .btn elements.
$('.btn').each(function() {
$(this).click(function() {
if ($(this).hasClass("selected")) {
$(this).removeClass("selected");
} else {
$(this).addClass("selected");
}
});
})
.selected { background-color:red }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="lorem" class="btn">Lorem</div>
<div id="ipsum" class="btn">Ipsum</div>
<div id="dolor" class="btn">Doloe</div>
<div id="Set" class="btn">Set</div>
You've over complicated this a little. Firstly you don't need an each() loop as the click() will be applied to a collection of elements if you provide them in the selector. Secondly you can use toggleClass() on the element which is clicked. Then you can use removeClass() on all the other .btn elements to remove the class. Try this:
var $btns = $('.btn').click(function() {
$btns.not(this).removeClass('selected');
$(this).toggleClass("selected");
});
.selected {
color: #C00;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="lorem" class="btn">Lorem</div>
<div id="ipsum" class="btn">Ipsum</div>
<div id="dolor" class="btn">Doloe</div>
<div id="Set" class="btn">Set</div>
You do not need each nor else; toggleClass and remove from siblings will work
$('.btn').on("click",function() {
$(this).toggleClass("selected");
$(this).siblings().removeClass("selected");
})
.selected { background-color:red }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="lorem" class="btn">Lorem</div>
<div id="ipsum" class="btn">Ipsum</div>
<div id="dolor" class="btn">Doloe</div>
<div id="Set" class="btn">Set</div>
To fix your existing code, remove all classes from all buttons in the else:
$('.btn').each(function() {
$(this).click(function() {
if ($(this).hasClass("selected")) {
$(this).removeClass("selected");
} else {
$('.btn').removeClass("selected");
$(this).addClass("selected");
}
});
})
.selected {
background-color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="lorem" class="btn">Lorem</div>
<div id="ipsum" class="btn">Ipsum</div>
<div id="dolor" class="btn">Doloe</div>
<div id="Set" class="btn">Set</div>

How I hide a div when jquery show another div?

I want that when the click activate the element2 div, the element should disappear. And the element2 div should not appear at the beginning.
$(".toggle").click(function() {
$(".element2").toggle();
});
$(".close").click(function() {
$(".element2").hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="element">
Element 1
<div class="toggle">
toggle
</div>
<div class="element2">
Element 2
<div class="close">close Element 2</div>
</div>
</div>
Add display none to hide an element from the start:
<div class="element2" style="display:none">
The rest of your code appears to be doing what it's supposed to, unless I am misunderstanding "I want that when the click activate the element2 div, the element should disappear"... which is entirely possible.
In order to have element2 hidden at the beginning you need to either add a style tag or even better add a CSS file where you will keep all of your stylings in one place.
For style tag:
<div class="element2" style="display:none">
For CSS:
.element2 {
display: none;
}
Then for your code you are close. In order to make element hide, you need to change it to:
$(".toggle").click(function() {
$(".element2").show();
$(".element").hide();
});
$(".close").click(function() {
$(".element2").hide();
$(".element").show();
});
The HTML will need some changes to, this will make what I wrote work the way I believe you want it to:
<div class="element">
Element 1
<div class="toggle">
toggle
</div>
</div>
<div class="element2">
Element 2
<div class="close">close Element 2</div>
</div>
You should probably do something like this:
$(".toggle").click(function() {
$(this).parent().find(".element2").toggle();
});
$(".close").click(function() {
$(this).parent().hide(); // close the correct .element2
});
In CSS you need to:
.element2 {
display: none;
}
just $(".element2").hide(); hide it at start
$(function() {
$(".element2").hide();
$(".toggle").click(function() {
$(".element2").toggle();
});
$(".close").click(function() {
$(".element2").hide();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="element">Element 1
<div class="toggle">Toggle </div>
<div class="element2"> Element 2
<div class="close"> close</div>
</div>
</div>
HTML
<div class="element">
<div class="toggle"></div>
<div class="element2" style="display:none">
<div class="close"></div>
</div>
</div>
EXAMPLE CSS
.toggle
{
display:block;
width:20px;
height:20px;
margin-left:10px;
float:left;
background:green;
}
.element2{
display:block;
width:40px;
height:40px;
margin-left:10px;
float:left;
background:yellow;
}
.close{
display:block;
width:20px;
height:20px;
margin-left:10px;
float:right;
border:1px solid #000;
}
JQUERY
$(".toggle").click(function() {
$(".element2").toggle();
});
$(".close").click(function() {
$(".element2").css({"display":"none"});
});
fiddle to check
I hope it is helpfull answer. Good Luck !

At a time the panel color is changing only once after cloning the main div

Here i'm trying to clone a <div class="main" and i need to change the color of this parent div.but at a time its changing only once (only first panel) after the cloning. Also cloning repeating multiple time on a button click while i need to clone it only once on every button click. Can someone help me to solve this?
Here is the code link: https://jsfiddle.net/Issact/k69pxad9/
<div class="body">
<div class="main">
<div class="inner">
<div class="content">
This is a test content
</div>
</div>
<button type="button" class="ChangeColor">
Change color
</button>
</div>
<Button type="button" class="clickButton">
Click on button
</Button>
</div>
CSS:
.main {
background-color:#000;
color:#fff;
font-size:18px;
padding-bottom:15px;
padding-left:15px;
}
.inner {
padding:15px;
}
JS:
$(document).ready(function(){
$('.clickButton').click(function(){
$('.main').clone().appendTo('.body');
});
$('.ChangeColor').click(function(){
$(this).parent('.main').css({backgroundColor: 'green'});
});
});
Use delegate click event for dynamically created element please find below sample for you case.
I would recommend to use .on below is a signature of .on function
$(document).on( eventName, selector, function(){} );
$("body").on("click", "#YOUR_DYNAMICALLY_CREATED_ELEMENT", function(event){
//Do Some stuff
});
// Your case it would be like below
$(document).on('click','.ChangeColor',function(){
$(this).parent('.main').css({backgroundColor: 'green'});
});
FIDDLE
$('.clickButton').click(function(){
$('.main').clone().appendTo('.body');
$('.ChangeColor').click(function(){
$(this).parent(".main").css({backgroundColor: 'green'});
});
});
You try to add an event, before the Node is created.
Add with eq(0).Its clone only the one main element .And change the ChangeColor click function with on() .Because dynamically append element not working normal click
$(document).ready(function() {
$('.clickButton').click(function() {
$('.main').eq(0).clone().appendTo('.body');
});
$(document).on('click','.ChangeColor',function() {
$(this).parent('.main').css({
backgroundColor: 'green'
});
});
});
.main {
background-color: #000;
color: #fff;
font-size: 18px;
padding-bottom: 15px;
padding-left: 15px;
}
.inner {
padding: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="body">
<div class="main">
<div class="inner">
<div class="content">
This is a test content
</div>
</div>
<button type="button" class="ChangeColor">
Change color
</button>
</div>
<Button type="button" class="clickButton">
Click on button
</Button>
</div>
Since you're creating your .main element dynamically, the javascript code you used will not work(since those elements are not yet created) & you need to use "event delegation" method to make it work.
$('.body').on('click', '.ChangeColor', function() {
$(this).parent('.main').css({backgroundColor: 'green'});
});
Explanation:
Instead of binding the "click" event handler directly to the dynamically creating element(.ChangeColor), you can instead bind it to a parent element(.body or <body> or document) & watch for a change/addition of new child elements.
Read more about delegation from here
It is because the elements created by .clone() don’t bind handlers.
Use
$('.body').on('click', '.clickButton', function(){
$('.main').clone().appendTo('.body');
});
to resolve it

Categories