jQuery toggleClass doesn't switch class - javascript

i've been trying to understand toggleClass function by making this simple script, yet it didn't work the way I expected it to.
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<style type="text/css">
body {
font-family: "Kozuka Gothic Pro";
}
.red {
background: red;
}
.blue {
background: blue;
}
div {
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<div class="blue"></div>
<script>
$("div").click(function() {
$(this).toggleClass("red");
});
</script>
</body>
However, if i changed the div class to red and the toggleClass argument to "blue" it works, can anybody explain me this? I'm hoping to hear from you. Thanks in advance!

You need to add both blue and red class in toggleClass function to change both like,
$("div").click(function() {
$(this).toggleClass("red blue");
});
$("div").click(function() {
$(this).toggleClass("red blue");
});
body {
font-family: "Kozuka Gothic Pro";
}
.red {
background: red;
}
.blue {
background: blue;
}
div {
width: 200px;
height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="blue"></div>
What happens when you use only red in togleclass function then it will applied but the change would not overwrite because of the blue class and the blue background shown as it is. So, if you want your code to work then in that case you need to use !important in red-background like,
.red {
background: red !important;
}
$("div").click(function() {
$(this).toggleClass("red");
});
body {
font-family: "Kozuka Gothic Pro";
}
.red {
background: red !important;
}
.blue {
background: blue;
}
div {
width: 200px;
height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="blue"></div>
Note that I am just informing you (by second alternative) why your code was not working. You must go with my first option.

$("div").click(function() {
$(this).toggleClass("red");
$(this).toggleClass("blue");
});
body {
font-family: "Kozuka Gothic Pro";
}
.red {
background: red;
}
.blue {
background: blue;
}
div {
width: 200px;
height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="blue"></div>
$("div").click(function() {
$(this).toggleClass("red");
$(this).toggleClass("blue");
});

Try this : pass both red and blue class, it will remove if present and add if not. So for first time it will add red but will remove blue.
$("div").click(function() {
$(this).toggleClass("red blue");
});

The toggleClass() method toggles between adding and removing one or more class names from the selected elements.
This method checks each element for the specified class names. The class names are added if missing, and removed if already set - This creates a toggle effect.
Explanation Below
it act as - if div have class "red" then REMOVE class "red" else ADD "red" class from div

The problem arises due to order of the css styles, as last css style will affect the output, so as css on class blue is declared last, so blue class is given precedence over red class.
So, to solve this, you should try to have only one class on the div, so that the order of the css should not matter.
$("div").click(function() {
$(this).toggleClass("red blue");
});

The toggleClass() will remove the class if it is assigned to the element, or it will add it if it is not assigned to the element. Try this snippet as a demo:
$(document).ready(function() {
$("div").click(function() {
if ($(this).hasClass("red")) {
alert("I am red! I'm turning red off.");
$(this).toggleClass("red");
} else if ($(this).hasClass("blue")) {
alert("I am blue! I'm turning blue off.");
$(this).toggleClass("blue");
} else {
alert("I am blank! Turning red on.");
$(this).toggleClass("red");
}
});
});
body {
font-family: "Kozuka Gothic Pro";
}
.red {
background: red;
}
.blue {
background: blue;
}
div {
width: 200px;
height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="blue"></div>

Related

How do i toggle between multiple classes for multiple elements in jQuery?

So I'm trying to implement a set of functions on my website with multiple div objects in it, so that when I click on Div A, it sets the text color of the page to red through Class A, and when i click on Div B, it sets the text to green through Class B, and so on and so forth.
My issue is that the other classes don't unset when clicking multiple objects and one class overrides the others, so the color of the text won't switch anymore.
I've been looking for solutions and trying to use addClass() and removeClass(), but it doesn't work for some reason. Here is a snippet of my code here
$(function() {
$('.one').click(function() {
$("h1").addClass('onetxt');
$("h1").removeClass('twotxt, threetxt');
});
});
$(function() {
$('.two').click(function() {
$("h1").addClass('twotxt');
$("h1").removeClass('onetxt, threetxt');
});
});
$(function() {
$('.three').click(function() {
$("h1").addClass('threetxt');
$("h1").removeClass('onetxt, twotxt');
});
});
h1 {
text-align: center;
}
div {
height: 65px;
width: 65px;
margin: 20px auto;
border-style: solid;
}
/*style info, ignore above here*/
.one {
background-color: red;
}
.onetxt {
color: red;
}
.two {
background-color: green;
}
.twotxt {
color: green;
}
.three {
background-color: blue;
}
.threetxt {
color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Sample Text</h1>
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
Any help on this would be greatly appreciated, and if you need more info, ask me in the replies, thank you!
EDIT: Here's a JSFiddle link demonstrating the code that i currently have, my intention is for all three of the DIV elements to change the top text's color when selected in any order, with using the classes if possible.
It seems like the main issue is that removeClass doesn't support multiple class selectors (like 'onetxt, twotxt'). Also you aren't removing all possible classes depending on the order of clicks.
Here's a solution that might work. I've written some helper functions which hopefully clarify what's going on.
const targets = 'h1, p'
const classmap = {
one: 'onetxt',
two: 'twotxt',
three: 'threetxt'
}
const allclasses = Object.values(classmap);
function clearSelection() {
allclasses.forEach(function(clz) { $(targets).removeClass(clz) });
}
function addSelection(sel) {
$(targets).addClass(classmap[sel]);
}
$(function() {
$('.one').click(function(){
clearSelection();
addSelection('one')
});
});
$(function() {
$('.two').click(function(){
clearSelection();
addSelection('two')
});
});
$(function() {
$('.three').click(function(){
clearSelection();
addSelection('three')
});
});
Here's a vanilla DOM API solution based on classList.toggle(className: string, force: boolean). The second parameter controls whether toggle works as remove or add.
const classes = ['one', 'two', 'three'];
classes.forEach(clazz => {
document.querySelector(`.${clazz}`).addEventListener('click', () => {
classes.forEach(cl => document.querySelector('h1').classList.toggle(`${cl}txt`, cl === clazz));
})
})
h1 {
text-align: center;
}
div {
height: 35px;
width: 35px;
margin: 5px auto;
border-style: solid;
}
/*style info, ignore above here*/
.one {
background-color: red;
}
.onetxt {
color: red;
}
.two {
background-color: green;
}
.twotxt {
color: green;
}
.three {
background-color: blue;
}
.threetxt {
color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Sample Text</h1>
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
There is no .removeClass() overload supports multiple argument, it only remove the first class. .removeClass() with no argument remove all the classes. This maybe the one you need.
I tweak your code a little bit, including:
Rename some class name. .color-palette is the container of all color selection. .color is individual color choice box.
Add data-color-name attribute to .color. The attribute will be used for sample-text css class assignment.
Simplify the click event with a single, event-delegate handler. I try to decouple the add/remove class logic with the actual color name. This way if you have more color boxes to add, you do not need to copy a new set of function.
Define custom css property. E.g. (--color-1, --color-2). The same property is used for color box background and sample text font color. You don’t have to maintain colors in two different place.
$('.color-palette').on('click', '.color', function(e) {
$("#sample-text").removeClass().addClass($(e.currentTarget).data('color-name'));
});
/* maintain the color choices here */
:root {
--color-1: red;
--color-2: green;
--color-3: blue;
}
h1 {
text-align: center;
}
.color {
height: 65px;
width: 65px;
margin: 20px auto;
border-style: solid;
}
/* style info, ignore above here */
/* color palette style */
.color.color-1 {
background-color: var(--color-1);
}
.color.color-2 {
background-color: var(--color-2);
}
.color.color-3 {
background-color: var(--color-3);
}
/* sample text style */
#sample-text.color-1 {
color: var(--color-1);
}
#sample-text.color-2 {
color: var(--color-2);
}
#sample-text.color-3 {
color: var(--color-3);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1 id="sample-text">Sample Text</h1>
<div class="color-palette">
<div class="color color-1" data-color-name="color-1"></div>
<div class="color color-2" data-color-name="color-2"></div>
<div class="color color-3" data-color-name="color-3"></div>
</div>

If hasClass condition not working after Updating Class with jQuery

Here is jQuery condition if hasclass not working when i update class from Jquery, What is reason ? Means if i change / Update class then also Jquery if condition working on click, Rather it should not work after that.
in my case, first of all the div Some Content has class .L2D1 that's color is blue okay, then my jQuery condition is if Some Content has class .L2D1 means till its color is blue then it should should change the color of Some Other Content div that's red.
But when i changed the class .L2D1 from jQuery Onclick change class button, then it's class changed into .newClass then also my jQuery if condition working Why?
Where i am making mistake, plz make it solve. literally I don't able to get actual problem.
See this:
$('.ChangeClass').click(function () {
$(".L2D1").attr('class', 'newClass');
});
$(document).ready(function(){
if ($("#L2D1-id").hasClass("L2D1")) {
$('.ChangeColor').click(function () {
$(".Layout-2").addClass('intro');
});
}
});
.intro {
font-size: 120%;
color: red;
}
.newClass {
font-size: 120%;
color: green;
}
.L2D1 {
font-size: 100%;
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div class="L2D1" id="L2D1-id"> Some Content </div>
<div class="Layout-2"> Some Other Content </div>
<button class="ChangeClass">Change Class</button>
<button class="ChangeColor"> <!-- if ($("#L2D1-id").hasClass("L2D1")) Then { --> Change Color</button>
Your event is created when your script is loaded. So the if statement is never tested after
To solve it you can put the if statement into your event, like :
$('.ChangeClass').click(function() {
$(".L2D1").attr('class', 'newClass');
});
$(document).ready(function() {
$('.ChangeColor').click(function() {
if ($("#L2D1-id").hasClass("L2D1")) {
$(".Layout-2").addClass('intro');
}
});
});
.intro {
font-size: 120%;
color: red;
}
.newClass {
font-size: 120%;
color: green;
}
.L2D1 {
font-size: 100%;
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div class="L2D1" id="L2D1-id"> Some Content </div>
<div class="Layout-2"> Some Other Content </div>
<button class="ChangeClass">Change Class</button>
<button class="ChangeColor"> <!-- if ($("#L2D1-id").hasClass("L2D1")) Then { --> Change Color</button>

jquery.hover() adds class and removes it immediatly

I cannot show any pen, I can just describe the bug. This is my javascript:
$(".vetrina-deluxe-info-container-front").hover(function() {
$(this).closest('.js-in-viewport-hook').addClass("in-viewport");
}, function() {
$(this).closest('.js-in-viewport-hook').removeClass("in-viewport");
});
On the first .hover() on any of these elements, the class is added and immediately removed. From the second time I hover everything works fine.
I've also tried this code:
$(".vetrina-deluxe-info-container-front").mouseover(function() {
$(this).closest('.js-in-viewport-hook').addClass("in-viewport");
});
$(".vetrina-deluxe-info-container-front").mouseleave(function() {
$(this).closest('.js-in-viewport-hook').removeClass("in-viewport");
});
It has the exact same behavior. I have also tried to change the .hover() div to see if anything changes but no. Any ideas or workaround?
I've tried in diferents elements.
$('.test').mouseover(function(e){
console.log('ON');
$(this).removeClass('blue');
$(this).addClass('red');
}).mouseout(function(e){
$(this).removeClass('red');
console.log('OUT');
$(this).addClass('blue');
});
$('#test').mouseenter(function(e){
console.log('IN');
$(this).removeClass('red');
$(this).addClass('yellow');
}).mouseleave(function(e){
$(this).removeClass('yellow');
$(this).removeClass('yellow');
console.log('OUT');
$(this).addClass('red');
});
.test{
width: 60%;
height: 60%;
margin: 10px auto;
}
.yellow{
background-color: yellow;
}
.red{
background-color: red;
}
.blue{
background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<div class="test yellow">
<p>TEST</p>
</div>
</html>
Your code will be like:
$(".vetrina-deluxe-info-container-front").mouseenter(function() {
$(this).closest('.js-in-viewport-hook').addClass("in-viewport");
}).mouseleave(function() {
$(this).closest('.js-in-viewport-hook').removeClass("in-viewport");
});
Did you try this code:
$(".vetrina-deluxe-info-container-front").hover(function() {
$(this).closest('.js-in-viewport-hook').toggleClass("in-viewport");
});
please check this i have added class on hover then i remove the class name when not hovered
<p>hover me.</p>
<script>
$("p").hover(function(){
$(this).css({"color":"blue"}).addClass('color-blue');
}, function(){
$("p").css({"color":"red"}).removeClass('color-blue');
});
</script>
https://jsfiddle.net/gapqc5wb/

After javascript addclass it adds class but css property not working

Can please someone help me?
Here .header-line after scroll has an additional class of .header-line .active but css can't see it and doesn't change the background-color. You can see my css and there .header-line .active is with background-color property. Why is my background still transparent?
CSS:
.header-line {
width: 100%;
height: 60px;
background-color: rgba(255,255,255,0.00);
}
.header-line .active {
background-color: white;
}
header:
<div class="header-line">header</div>
Javascript:
$(function() {
$(window).on("scroll", function() {
if($(window).scrollTop() > 50) {
$(".header-line").addClass("active");
} else {
//remove the background property so it comes transparent again (defined in your css)
$(".header-line").removeClass("active");
}
});
});
That is because in your css file you have .header-line .active { ... }, and that means .active class inside .header-line class.
You should change that to .headerline.active { ... } (remove the space)
Declare the css like this in your bootstarp.css
.header-line.active {
background-color: white;
}

setTimeOut and hover

I was playing around with learning some JavaScript and this small code didn't work for me. If I take out the setTimeout function, the hover works again.
Why doesn't the hover work?
https://jsfiddle.net/jzhang172/1n8gqeom/
setTimeout(
function(){
$(".div").css("background","blue");}, 100);
.div{
background:black;
height:50px;
width:50px;
}
.div:hover{
background:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div"></div>
$(".div").css("background","blue");}, 100);
With this line of code, you are adding inline style to the .div, so it has higher specificity.
Try something like this:
setTimeout(
function() {
$(".div").addClass('someClass');
}, 100);
.div {
background: black;
height: 50px;
width: 50px;
}
.div:hover {
background: red;
}
.someClass {
background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div"></div>
css priority。 inline style > class style, so, cover
.div:hover{
background:red !important;
}

Categories