Switch CSS class everytime user clicks - Jquery - javascript

I have 2 links with different CSS classes.
How can I switch between the two everytime a the user clicks?
<a class="class1" id="class1">Class1</a>
<a class="class2" id="class2">Class2</a>
It's just work one time, but when I click a second time, it doesn't work:
$("#class1").click(function(){
$("#class1").removeClass().addClass("class2");
$("#class2").removeClass().addClass("class1");
})
$("#class2").click(function(){
$("#class1").removeClass().addClass("class2");
$("#class2").removeClass().addClass("class1");
})
The CSS is to change the color

The methods are doing the same thing. You set the same class to each tag in both thats why it only works the first time. The second time it just resetting the current class.
Shouldn't they be like this instead?
$("#class1").click(function(){
$("#class1").removeClass().addClass("class2");
$("#class2").removeClass().addClass("class1");
})
$("#class2").click(function(){
$("#class1").removeClass().addClass("class1");
$("#class2").removeClass().addClass("class2");
})

You can use toggleClass to switch multiple classes..
$('.red,.blue').click(function() {
$(this).toggleClass('red blue');
});
.red { background-color:red }
.blue { background-color:blue }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="red">One</div>
<div class="blue">Blue</div>

You can use selector "[class^=class]" to select elements where Element.className begins with "class"; use .slice() with parameters 0, -1 to select characters in string up to last character; check if last character is 1 or 2 using == equal operator; set the opposite last character for matches 1: "2", 2: "1" at last character of Element.className
$("[class^=class]").click(function() {
var c = this.className;
this.className = c.slice(0, -1) + (c[c.length - 1] == 1 ? 2 : 1);
});
.class1 {
color: blue;
}
.class2 {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="class1" id="class1">Class1</a>
<a class="class2" id="clas2">Class2</a>

Done using toggleClass JSFIDDLE:https://jsfiddle.net/kameeshwaran/5puecqeq/
HTML:
<a class="class1" id="class1">Class1</a>
<a class="class1" id="class2">Class2</a>
JS
$(document).ready(function(){
$(".class1").click(function(e){
e.preventDefault();
$(this).toggleClass("class2")
});
});
CSS:
.class1{
background-color:green;
}
.class2{
background-color:red;
}

When you click class1 once, it removes the class class1 from class1, and puts class2 on.
However, when you click it again, because class1 is set to the class class2, it won't change.
You should probably do something like this:
var class1check = 0;
$("#class1").click(function() {
if (class1check === 0) {
var addclass1 = "class2";
var addclass2 = "class1";
}
else {
var addclass1 = "class1";
var addclass2 = "class2";
class1check = 0;
}
$("#class1").removeClass().addClass(addclass1);
$("#class2").removeClass().addClass(addclass2);
});

Related

Add class to next integer on click while removing from current jQuery

I am wrapping the class; slideVisible to the first 3 blog articles displayed. This class removes the css property; display - none. I have added some indicators with the class; carousel-buttons, which also is based on the number of loops of sets of 3 blog posts. On click of these carousel-buttons I would like to remove the class slideVisible from the element which currently has it, and then add to the next element in the sequence.
I have used an index-related selector to demonstrate a way of creating this function, however this is not dynamic. How would I do this correctly?
jQuery(document).ready(function() {
var carosuelPost = jQuery(".post-slider-mango .post");
jQuery('.post-slider-mango .fusion-posts-container').wrapAll('<div id="dog-slider"><div class="carousel-inner"></div></div>');
for (var i = 0; i < carosuelPost.length; i += 3) {
let activeClass = '';
if(i == 0) activeClass = 'slideVisible';
carosuelPost.slice(i, i + 3).wrapAll('<div class="slideElements ' + activeClass + '"> </div>');
}
for (var i = 0; i < carosuelPost.length; i += 3) {
if(i == 0) activeClass = 'slideVisible';
jQuery(".post-slider-mango .fusion-posts-container").after('<a class="carousel-buttons"><li></li></a>');
jQuery(".carousel-buttons:eq(0)").on("click", function() {
jQuery(".slideElements").removeClass("slideVisible");
jQuery(".slideElements:eq(0)").addClass("slideVisible");
});
jQuery(".carousel-buttons:eq(1)").on("click", function() {
jQuery(".slideElements").removeClass("slideVisible");
jQuery(".slideElements:eq(1)").addClass("slideVisible");
});
}
});
So it's hard to say because it depends on the element that has the activeClass class and the heirarchy. You can have the .carousel-button on click remove the class from its parent, or parent's parent.
You can use .closest() to find the closest ancestor with x class. So:
// Declare function that removes a given class from given element
// Set click event listener for .carousel-button elements
$('.carousel-button').click(function(e){
e.preventDefault();
$(this).closest('div.slideVisible').removeClass('slideVisible');
});
Also to note, I would use a <button> element for the carousel-button so you do not then need to use the e.preventDefault() in the click event. If it is only to be used to run JavaScript via user interaction then you do not need to use an <a> tag.
See snippet for working example.
// Set click event listener for .carousel-button elements
$('.carousel-button').click(function(){
const next = $(this).closest('div.slideVisible').next().is('.slide');
if (next) {
return $(this).closest('div.slideVisible').removeClass('slideVisible').next().addClass('slideVisible');
} else {
return $(this).closest('div.slideVisible').removeClass('slideVisible').prev().addClass('slideVisible');
}
});
.slide {
display:none;
padding:2rem;
text-align:center;
background:orange;
}
.slide2 {
background:yellow;
}
.slideVisible {
display:block;
}
.carousel-button {
padding:1rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="slide slide1 slideVisible">
<div class="buttons">
<button class="carousel-button">Hide Me!</button>
</div>
</div>
<div class="slide slide2">
<div class="buttons">
<p>This is slide 2</p>
<button class="carousel-button">Hide Me!</button>
</div>
</div>
Edit: This answer assumes that you're trying to remove the class from a parent of the button you're clicking. If you need to get it from the sibling before or after you can use .prev() and .next() after calling the .closest() method:
$(this).closest('div.slideVisible').prev().removeClass('slideVisible');

Edit div class name on click

So basically I have a bunch of nav buttons that I want to change the name of when the user clicks the button.
The original div class name is something like "home", and when the user clicks on it I want it to be "home_active" so that the CSS attributes will change the background-image.
$('.click').click(function() {
var clicked_url = $(this).attr('class');
var updated_url = clicked_url + "_active";
$(this).attr('class') = updated_url;
});
.item_active {
background-color: teal;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
item 1
item 2
item 3
You shall use the .addClass() method add a class to the element:
$('.click').click(function() {
var clicked_url = $(this).attr('class');
var updated_url = clicked_url + "_active";
$(this).removeClass(clicked_url); // remove the old class
$(this).addClass(updated_url); // add the new class
});
However, as a good practice, it is better to add a modifier class, such as "active" to the existing class, preserving the original class name.
Then use the following CSS:
.click.active {
background: red;
}
The JS code would look like this:
$('.click').click(function() {
$('.click.active').removeClass('active'); // remove active class from all other nav items
$(this).addClass('active'); // add active to the nav item the users just clicked on
});
Using Jquery functions:
$(this).hasClass("className");
$(this).addClass("className");
$(this).removeClass("className");
$('.click').click(function() {
var clicked_url = $(this).attr('class');
var updated_url = clicked_url + "_active";
$(this).removeClass(updated_url)
$(this).addClass(updated_url)});
Almost there - but remember to use attr to reset the class value. And you most likely want to remove _active from the other .click elements, so this is the only one.
$(".click").click(function() {
$(".click").each(function() {
$(this).attr("class", $(this).attr("class").replace(/_active/, ""));
});
$(this).attr("class", $(this).attr("class") + "_active");
});
Not sure where class .click is but there is .item and .click(...) method is ok -- I prefer to use .on('click', ...) (see the difference between .click() and .on()).
$('.item').on('click', function() {...
Since objective is to simply change the style of a clicked link by changing its class then it's better to assign a common class (which was done: .item) and a class that sets the state (a separate class: .active).
$(this).toggleClass('active');
If you wish to apply this to additional tags, simply modify the outer selector
$('.item, :button').on('click', function() {...
The selector above will listen for clicks on anything with the class .item and any <button> and <input type='button'> tags.
It wasn't very clear what the desired behavior was so there's two demos:
Demo 1: Click any link to add/remove .active class
or
Demo 2: Click any link to add/remove .active class exclusively
Demo 1
Click any link to add/remove .active class
$('.item').on('click', function() {
$(this).toggleClass('active');
});
.active {
background-color: teal;
color: white
}
item 1
item 2
item 3
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Demo 2
Click any link to add/remove .active class exclusively
$('.item').on('click', function() {
$(this).toggleClass('active');
$('.item').not(this).removeClass('active');
});
.active {
background-color: teal;
color: white
}
item 1
item 2
item 3
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Couple things. First, you want to select elements with a class name of "item," not "click." Secondly, you were using the attr() function wrong. Instead of attr('class') = var, you want to set the var as the second parameter, e.g. attr('class', var).
Edit: Finally, you should check in your click event whether or not the link has been previously clicked (i.e. whether it already has the "_active" suffix):
$('.item').click(function() {
var clicked_url = $(this).attr('class');
var updated_url;
if(clicked_url.includes("_active")){
updated_url = "item";
}else{
updated_url = "item_active";
}
$(this).attr('class', updated_url);
});
.item_active {
background-color: teal;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
item 1
item 2
item 3

Get color of DIV in hex format JQuery

This is my code:
function getTraits(trait) {
$("#"+trait).on("click", function() {
alert($(this).css('backgroundColor'));
if (toHex($(this).css('background-color')) != highlightedColor) {
$("#"+trait).css("background-color", highlightedColor);
// If the element isn't highlighted, highlight it.
} else {
$(this).css("backgroundColor", defaultColor);
}
})
}
I am trying to toggle a highlight on a div on the user's click. I would like to get the background color of the div because it would be inefficient to store a boolean toggle for each and every div. So I want a toHex(rgb) function. I saw a lot of those on SO, so I tried using them and none of them worked. The alert() I put to show me the format JQuery was returning gave me rgba(0,0,0,0). I attempted to modify a regex I found like this:
var rgb = rgb.match(/^rgba((\d+),\s*(\d+),\s*(\d+))$/);
That failed to work with a TypeError: rgb is null.
Thanks for any help you can give me!
I know, not the answer to your question, but have you considered jQuery's toggleClass() option?
Define a highlighted CSS class:
DIV.default { background-color: whitesmoke; }
DIV.highlighted { background-color: yellow; }
and then when the user clicks your DIV:
function getTraits(trait) {
$("#"+trait).on("click", function() {
// Toggle both classes so as to turn one "off"
// and the other "on"
$(this).toggleClass('default');
$(this).toggleClass('highlighted');
// Ensure we have at least one class (default)
var hasOne = $(this).hasClass('highlighted') || $(this).hasClass('default');
if (!hasOne) {
$(this).addClass('default');
}
})
}
First of all get Background-Color and use the below function to convert it into HEX Value
var rgb=$(selector).css('background-color');
var hexColor=rgb2hex(rgb);
function rgb2hex(rgb) {
rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
return (rgb && rgb.length === 4) ? "#" +
("0" + parseInt(rgb[1], 10).toString(16)).slice(-2) +
("0" + parseInt(rgb[2], 10).toString(16)).slice(-2) +
("0" + parseInt(rgb[3], 10).toString(16)).slice(-2) : '';
}
Your problem: jquery will return rgba(0, 0, 0, 0) if there is no background color set (i.e. it is undefinied / null). The problem you have is that you are trying to parse an undefined rgb string into the hex converter.
I've added a clause into the converted from here, so that it returns white if the value is unset but this would need uncommenting, and isn't advised.
Advised solution is to use toggleClass, see the demo further down, showing how you can toggle higlighting on indiviidual elements or entire DOM trees.
Demo of rgb issue
// Cycle through each div
$("#example-wrap div").each(function() {
// Store rgb color
var rgb = $(this).css('backgroundColor');
// Print rgb color to the div
$(this).append( ": " + rgb);
// Append the hex value
$(this).append(" -> " + rgb2hex(rgb));
});
function rgb2hex(rgb) {
rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
function hex(x) {
return ("0" + parseInt(x).toString(16)).slice(-2);
}
// Check if rgb is null
if (rgb == null ) {
// You could repalce the return with a default color, i.e. the line below
// return "#ffffff"
return "Error";
}
return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}
#example-wrap div {
border: 1px solid black;
width: 100%;
height: 50px;
color: black;
}
#example-wrap .background-blue {
background: blue;
color: white;
}
#example-wrap .background-white {
background: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="example-wrap">
<div id="background-set" style="background-color: red; color: white;">Background set in 'style' attribute</div>
<div id="background-class" class="background-blue">Background set to blue via class</div>
<div id="background-class" class="background-white">Background set to white via class</div>
<div id="background-none">No background set</div>
</div>
Highlight via Toggle Class
This example lets you highlight individual elements tagged with .highlightable, as well as applying wrappers which mean all their children are highlightable via the class .highlightable-wrapper.
// Add click event to highlightable elements and wrappers
$(document).on("click", ".highlightable, .highlightable-wrapper *", function(e) {
// Toggle highlight class
$(this).toggleClass("highlight-me");
// Stop click event from propogating (i.e. allow spans to be highlighted individually)
// Uncomment this if you want propogation
e.stopPropagation()
});
.highlight-me {
color: blue;
}
.highlightable-wrapper .highlight-me, .highlightable-wrapper .highlight-me * {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="example-wrapper">
<div class="highlightable">
<h4>Individual Element Example</h4>
This is an exampled of a div with the .highlightable class.
</div>
<hr style="margin: 20px 0px;">
<div class="highlightable-wrapper">
<h4>Wrapper Example</h4>
<p>I am a paragraph within an element with the .highlightable-wrapper class.</p>
<p>Click us to see us change <strong>I am a strong span, you can individually highlight me</strong>.</p>
</div>
</div>

Why classes change the order?

$("body").on("click", ".close", function() {
var class_test1 = 'class1 class2';
var class_test2 = 'class1 class3';
$('#id_test').removeClass(class_test1).addClass(class_test2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="id_test" class="class1 class2">
test
</div>
<button class="close">
test
</button>
If click on button, div#id_test should be change classes on class1 class3, but he change classes on class3 class1(classes change the order).
Why is this happening and have resolved problem?
P.S.: need change class1 class3 on class1 class2 - only in this order.
The reason is the following:
There are multiple classes overlapping with multiple clicks.
Let me explain:
When you click the button the first time, the classes "class1" and "class2" get removed. Then "class1" and "class3" gets attached.
However, if you click the button AGAIN, ONLY "class1" gets removed, making "class3" move to the first position (since there is no "class2" to remove anymore). Then "class1" gets re-added AFTER "class3" - resulting in "class3 class1".
Suggested solution:
$("body").on("click", ".close", function() {
var class_test2 = 'class1 class3';
$('#id_test').removeClass().addClass(class_test2);
});
This will remove ALL the classes and then adds the right ones in right order.
You can use .toggleClass() to toggle 2 , 3 at end of one of the className string
$("body").on("click", ".close", function() {
var n = 3;
$("#id_test").toggleClass(function() {
return "class2 class" + n;
})
});
#id_test.class2 {
color: green;
}
#id_test.class3 {
color: blue;
}
#id_test.class2:after {
content: attr(class);
}
#id_test.class3:after {
content: attr(class);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div id="id_test" class="class1 class2">
test
</div>
<button class="close">
test
</button>
try
$(".close").on("click", function() {
$('#id_test').removeClass("class2").addClass("class3");
});

how to make javascript function call two divs

i am trying to make a colour change when a button is clicked and i managed to do this however i want to change the colour of not just the main content container but more containers how do i do this?
function changeblackandwhite(objDivID) {
if(document.getElementById(objDivID).style.color=='black'){
document.getElementById(objDivID).style.color='white';
document.getElementById(objDivID).style.backgroundColor='black';
}
else if(document.getElementById(objDivID).style.color=='white'){
document.getElementById(objDivID).style.color='black';
document.getElementById(objDivID).style.backgroundColor = 'white';
}
else{
document.getElementById(objDivID).style.color='black';
document.getElementById(objDivID).style.backgroundColor='white';
}
}
<img src="images/colour.jpg" title="Change Text/Backgroud Colors">
There are dozens of ways you can accomplish this.
You could change the argument of your function to be an array of strings. You could also reduce the complexity of your function as well
<script type="text/javascript">
changeblackandwhite = function() {
for( var idx=0; idx < arguments.length; idx++) {
var tgtDiv= document.getElementById(arguments[i]);
if(tgtDiv.style.color=='black'){
tgtDiv.style.color='white';
tgtDiv.style.backgroundColor='black';
}
else{
tgtDiv.style.color='black';
tgtDiv.style.backgroundColor='white';
}
}
};
</script>
<img src="images/colour.jpg" title="Change Text/Backgroud Colors">
As another reader questioned - you can do this with jQuery in a single line.
With jQuery, you can declare the elements in question to have a class attribute.
Using jQuery, you can then do something like:
$('div.someClass').css({'color': 'black', 'background-color': 'white'});
The argument to jQuery can be a class based selector, an id based selector, or any other selector you choose.
If you are open to jquery and you assign 1 class in common with these two divs you can do the following:
This should get you started (see this jsfiddle): I changed the fiddle to include a neater solution where clicking on the button adds and removes classes on the containers which allows you to set multiple attributes including the text color in one quick call.
<div class='container'>
</div>
<div class='container'>
</div>
<button id="changeColor" type="button">Change Color </button>
<script type="text/javascript">
$(document).ready( function() {
$('#changeColor').click( function() {
if ($('.container').hasClass("blackContainer")){
$('.container').addClass("whiteContainer");
$('.container').removeClass("blackContainer");
} else {
$('.container').removeClass("whiteContainer");
$('.container').addClass("blackContainer");
}
});
});
</script>
//CSS
.blackContainer {
background-color: black;
color: white;
}
.whiteContainer {
background-color: white;
color: black;
}
I made a jsfiddle for you to play around with jsfiddle
I also did the javascript/jQuery in a similar way as the OP since it usually helps them understand.
As stated above, there are several different ways to do this, I've done but one.
The document.ready function sets up an event listener for the object to be clicked, most of the time this is how you'll see events coded. So when the link is clicked, it calls the function with the string name of the object the listener is for.
$(document).ready(function() {
$("#changeit").click(function(){
changeblackandwhite("Maincontainer");
})
});
After the event listener is assigned, it will call the function below when the link is clicked on.
// Here's your function, put the current color in a var, check if it's black
// if black, change colors, else make it black.
function changeblackandwhite(objDivID) {
var curColor = $("#" + objDivID).css("color");
if( curColor == 'rgb(0, 0, 0)'){
$("#"+objDivID).css({'color':'white','background-color':'black'});
} else {
$("#"+objDivID).css({'color':'black','background-color':'ghostwhite'});
}
}

Categories

Resources