how do i remove classes with jQuery? - javascript

how do i remove classes with jQuery?
I have this "template" i am working on and i want a "settings" box to the left where the user can change the "color scheme" of the navigation.
I have like 5-10 colors and i cant get it to work.
$(".color-orange").click(function () {
$("#nav").addClass("color-orange");
});
How can i then remove the class "color-orange" and add a new class if someone clicks on green?
Well i used this..
$(".color-green").click(function () {
$("#nav").removeClass("color-orange");
$("#nav").addClass("green");
});
But that just takes orange away. And will not work if you clicked another color..
Sorry for my english, and yes. Its my first time here :)
Kind Regards / Albin

Try this:
$("#nav").removeClass().addClass("green");
Without arguments removeClass will remove all the classes.
Also don't reselect $("#nav") again and again, use method chaining, this increases performance.

The below code will simply overwrite existing classes to whatever you set (in this case "green").
$("#nav").attr("class", "green");
Since this has gained enough upvotes, I'll tell you why this is kind of better answer than the above one. The one with removeClass().
First, you get the required element, that is $("#nav").
Then, you call a property of JQuery, removeClass().
Then, you again call another property of JQuery, addClass().
In the solution I suggested:
First, you get the element, then call the propery attr(), and that's it.
So, it's one step lesser.

How about this
$('[class^="color-"]').each(function() {
$("#nav").removeClass().addClass($(this).attr("class"));
}
or as xFortyFourx pointed out:
$('[class^="color-"]').each(function() {
$("#nav").attr("class",$(this).attr("class"));
}
Alternative - if I assume you have
.green { color:green; .... } /* for the nav */
.color-green { color:green; .... } /* for the settings */
you can do
$('[class^="color-"]').each(function() {
$("#nav").attr("class",$(this).attr("class").replace("color-",""));
}

Use removeClass and do not pass any class to removeClass and it will remove all classes that element has.
$(".color-green").click(function () {
$("#nav").removeClass().addClass("green");
});

$(".color-green").click(function () {
$("#nav").removeClass("color-orange");
$("#nav").removeClass("next-color");
$("#nav").removeClass("another-color");
$("#nav").removeClass("yet-another-color-but-green");
$("#nav").addClass("green");
});

Related

How to change CSS over selected element only using $(this)

I'm trying to make it where when the user .mouseover() the .featured_products the .featured_products, and the .button will apply the CSS affect to the selected container. The problem i'm encountering is it changes the .css of both the .feature_products containers. I'd like it to only change the one that's being .mouseover(). I tried using $(this) but i'm not understanding it correctly.
$(".featured_products").mouseover(function(){
$(".fp_button").css("background-color", "#00addc");
$(".fp_button").css("color", "#FFFFFF");
$(this).addClass("fp_hover");
});
$(".featured_products").mouseleave(function(){
$(".fp_button").css("background-color", "white");
$(".fp_button").css("color", "#000000")
$(".featured_products").removeClass("fp_hover");
});
Here is my Demo
You can use the second parameter in the selector to denote a parent, like:
$(".fp_button", this).css("background-color", "#00addc");
See it here: http://jsfiddle.net/4417zugn/31/
You can also do something like:
$(this).find(".fp_button")...
etc. There are many ways.
One thing I'd suggest is to change the class name instead of modifying individual CSS rules, like this: http://jsfiddle.net/4417zugn/33/
Last thing, this is all possible using only CSS, like this: http://jsfiddle.net/4417zugn/35/
There's no need to use jQuery to alter the CSS you can do that in the CSS itself using the :hover selector. You can then use jQuery to toggle the 'fp_hover' class.
$('.featured_products').hover(function(){
$(this).toggleClass('fp_hover')
})
https://jsfiddle.net/Lozgnz84/
$(".fp_button") is common for both the divs; so
instead of writing:
$(".fp_button").css("background-color", "white");
Write:
$(this).find('.fp_button').css("color", "#FFFFFF");
Hence, your code becomes
$(".featured_products").mouseover(function(){
$this = $(this);
$this.find('.fp_button').css({"background-color":"#00addc", "color":"#FFFFFF"});
$this.addClass("fp_hover");
});
$(".featured_products").mouseleave(function(){
$this.find('.fp_button').css({"background-color":"white", "color":"#000000"});
$this.removeClass("fp_hover");
});
demo here: http://jsfiddle.net/znnamrwn/
What you've described can be done without jQuery. If however you would like to use jQuery you could simply toggle a class on the product element.
$('.featured_products').on({
mouseenter: function() {
$(this).toggleClass('fp_hover');
},
mouseleave: function() {
$(this).toggleClass('fp_hover');
}
}, '.featured_product');
http://jsfiddle.net/bradlilley/uwxsr4hu
You can also do the above without jQuery by simple adding the following hover state in your css.
.featured_product:hover .fp_button {
background: #f00;
color: #000;
}
https://jsfiddle.net/bradlilley/9mwxo9o2/6/
Edit: You should also avoid using mouseover and use mouseenter instead.
Jquery mouseenter() vs mouseover()

using $(this) jquery to change another element

So, I know how to change an attribute for the same element you hover over...
$(".click2play").mouseover(function()
{
$(this).css({'visibility' : 'hidden'});
});
question Can I do the same thing but to affect another element only within the same 'click2play' div that was hovered?
maybe like?
$(".click2play").mouseover(function()
{
$(this).(#someotherdiv).css({'visibility' : 'hidden'});
});
Thanks everyone!
This code targets a div, within the current .click2play element. I believe that's what you were asking for :)
$(".click2play").mouseover(function() {
$('div.class_name', this).css({'visibility' : 'hidden'});
});
not very clear from the ques what you wanna do so ill ans for all the options i can guess of
1.if you wanna hide all the elements of class .click2Play then use
$('.click2Play').hover(function(){$('.click2play').hide()});
2.if you want to just hide the current element of all the elements having this class use
$('.click2Play').hover(function(){$(this).hide()});
3.if you wanna generalize it then you can use.selector property of the jquery object so that you would be able to use it like
$('.click2Play').hover(function(){$($(this).selector).hide()});
so now if you will change the class name from .click2Play to some other class it will work nicely and will hide all the elements of that class.
4. if you want to hide some element inside that of current element then
$('.click2Play').hover(function(){$(this).children('selector_of_child').hide()});
5.if all the elements of this class have an element inside them having some other class and you wanna hide them all then simple use each like this
$('.click2Play').hover(function(){$('.click2play').each(function(){$(this).children("selector_Of_Child").hide()})});
I would do like this:
$(".click2play").mouseover(function(){
$(this).hide();
});
But maybe it isn't what you want to do?
I suppose this :):
$(".click2play").mouseover(function(){
$(this).css({'visibility' : 'hidden'});
});
or better
$(".click2play").mouseover(function(){
$(this).hide();
});
You want to change some other div? Why would you need $(this)?
$(".click2play").mouseover(function(){
$("#someotherdiv").hide();
});
To change a single css attribute you can do:
$(".click2play").mouseover(function(){
$(this).css('visibility', 'hidden');
});
I hope it helps
(consider to see this link: http://marakana.com/bookshelf/jquery_tutorial/css_styling.html )
I believe most of the answers didn't payed attention to the question, which asks about removing a class. Here is the answer to both questions:
$('.click2play').bind('mouseenter mouseleave', function () {
$(this).removeClass('click2play'); // This line removes the current object's class click2play
$('jQUerySelector').removeClass('click2play'); // This will remove another element's class click2play
});

How can I use multiple Floating Help Dialogue by using 'class' instead of 'id'?

I need to use multiple floating help dialog boxes in a page. I have tried it by using 'display:block' and 'display:none' and used ID in javascript. I cannot use classes since I have multiple of them on the same page and if I use classes then all of them will be displayed/hide at the same time. However, as the number of help items are increasing in the page, I have to go back to the javascript and add more lines ...
for example:
$(document).ready(function() {
$("#help-icon1").click(function() {
$('#help-details1').css('display', 'block');
});
$("#help-icon2").click(function() {
$('#help-details2').css('display', 'block');
});
$("#help-icon3").click(function() {
$('#help-details3').css('display', 'block');
});
});
Each of them also have close icons and they should be disappeared if clicked on that close icon or clicked anywhere in the page. That means I have to write javascript functions 3 times for all the different close icons.
I tried to rely on jquery's "next" feature, but since there are many layers (div/p/span) in between the areas where the help icon is places and the help text, it becomes problamatic. Any idea or any better way to resolve this?
Thanks in advance.
I'm not quite sure I understand what you are looking for, but you can set up all the click handlers in one step, and have each one refer to itself in the handler:
jQuery(".help-icon").click(function() {
jQuery(this).css('display', 'block');
});
You can add additional class names to an element.
A div can be hidden by default, and a new class can be appended to it - to "overrule" the previous style (Hence the name Cascading Style Sheets)
<div class="hidden exception"></div>
If an element is clicked, you can append a new classname like so:
$('.target').addClass('newclass');
more info:
http://api.jquery.com/addClass/
I've not done it using JQuery but what you need is "unobtrusive javascript".
It does get done by using a class. Say you have images you all want highlighted:
<img src="pic1.png" onMouseover="this.src='hi_pic1.png';" />
so they all have the same behaviour. Give them a class:
<img src="pic1.png" class="hi" />
Then at load time, on in the script at the end of your page, yahoo-style, you write an initialisation to
- grab every element of the class
- add the event(s) you want
- set the event to use the appropriate data, e.g. by using this and by using systematic names like pic1 -> hi_pic1.
Hope this helps,
Charles
Have you tried the jQuery .each function?
EDIT: Like the following
$(".help-icon").each(function(idx, elm){
elm.click(function(){
...
})
});
If all of your help icons have the same class you can use jQuery's each function to loop through them, retrieve the associated id, replace "icon" with "detail" in the id (so #help-icon3 would become #help-detail3), and then use that to update the panel. Something like:
$(".help-icon").each(function() {
var detailsId = $(this).attr("id").replace("icon", "details");
$("#" + detailsId).css('display', 'block');
});
Let's just ASSUME that you need to use IDs for some unknown reason. Here's your answer to combine efforts:
$("#help-icon1").add("#help-icon2").add("#help-icon3").click(function() {
$(this).css('display', 'block');
});
Which equates to:
$("#help-icon1, #help-icon2, #help-icon3").click(function() {
$(this).css('display', 'block');
});
But really, you don't need to use unique IDs like this without some pretty good reasons.

Remove all classes except one

Well, I know that with some jQuery actions, we can add a lot of classes to a particular div:
<div class="cleanstate"></div>
Let's say that with some clicks and other things, the div gets a lot of classes
<div class="cleanstate bgred paddingleft allcaptions ..."></div>
So, how I can remove all the classes except one? The only idea I have come up is with this:
$('#container div.cleanstate').removeClass().addClass('cleanstate');
While removeClass() kills all the classes, the div get screwed up, but adding just after that addClass('cleanstate') it goes back to normal. The other solution is to put an ID attribute with the base CSS properties so they don't get deleted, what also improves performance, but i just want to know another solution to get rid of all except ".cleanstate"
I'm asking this because, in the real script, the div suffers various changes of classes.
Instead of doing it in 2 steps, you could just reset the entire value at once with attr by overwriting all of the class values with the class you want:
jQuery('#container div.cleanstate').attr('class', 'cleanstate');
Sample: http://jsfiddle.net/jtmKK/1/
Use attr to directly set the class attribute to the specific value you want:
$('#container div.cleanstate').attr('class','cleanstate');
With plain old JavaScript, not JQuery:
document.getElementById("container").className = "cleanstate";
Sometimes you need to keep some of the classes due to CSS animation, because as soon as you remove all classes, animation may not work. Instead, you can keep some classes and remove the rest like this:
$('#container div.cleanstate').removeClass('removethis removethat').addClass('cleanstate');
regarding to robs answer and for and for the sake of completeness you can also use querySelector with vanilla
document.querySelector('#container div.cleanstate').className = "cleanstate";
What if if you want to keep one or more than one classes and want classes except these. These solution would not work where you don't want to remove all classes add that perticular class again.
Using attr and removeClass() resets all classes in first instance and then attach that perticular class again. If you using some animation on classes which are being reset again, it will fail.
If you want to simply remove all classes except some class then this is for you.
My solution is for: removeAllExceptThese
Array.prototype.diff = function(a) {
return this.filter(function(i) {return a.indexOf(i) < 0;});
};
$.fn.removeClassesExceptThese = function(classList) {
/* pass mutliple class name in array like ["first", "second"] */
var $elem = $(this);
if($elem.length > 0) {
var existingClassList = $elem.attr("class").split(' ');
var classListToRemove = existingClassList.diff(classList);
$elem
.removeClass(classListToRemove.join(" "))
.addClass(classList.join(" "));
}
return $elem;
};
This will not reset all classes, it will remove only necessary.
I needed it in my project where I needed to remove only not matching classes.
You can use it $(".third").removeClassesExceptThese(["first", "second"]);

Creating conditional statements for JQuery

I have a very novice question, so apologies if the answer to this is obvious.
I am using JQuery to toggle the contents of items based on whether the item has been clicked. I have been able to successfully implement the toggle feature.
I now need to have it load with the first two items set to show() with the rest set to hide(). I have given a unique class name to these first 2 items. I know that I can simply do a $('div.activeitem').show() and then hide thee rest, but I'd prefer to setup a condition.
I am a JQuery novice, so I don't know how to target these elements or their classes in a conditional statement. I've searched google but have been unsuccessful. I want a conditional that asks if the div "newsinfo" also has the class "jopen" then show(), else hide().
Thanks for your help. I have attached my code to help you understand the context of my question:
<script type="text/javascript">
$(document).ready(function(){
// Here is where I'd like to implement a conditional
$('div.newsinfo').hide(); // this would be part of my else
$('h5.newstoggle').click(function() {
$(this).next('div').slideToggle(200);
return false;
});
});
</script>
How about simply
$('div.newsinfo').each(function(){
if($(this).hasClass('jopen')){
$(this).show()
}else{
$(this).hide();
}
});
there is hasClass() function. Better way is using toggleClass().
For example:
$('div.blocks').click(function(){
$(this).toggleClass('class_name');
});
after first click class will be added, after second - removed... and so on ^^
JQuery has an .hasClass function.
i.e.
if($(".selectableItem").hasClass("selected")){
//remove selection
$(".selectableItem").removeClass("selected");
}else{
//remove the selected class from the currently selected one
$(".selectableItem .selected").removeClass("selected");
//add it to this one
$(".selectableItem").addClass("selected");
}
Why don't you add a default css to jopen class to display: block and the others to display: none ?
something like
.newsinfo {display: none}
.jopen {display:block!important}
Just use selectors. For example, if all divs with the class "newsinfo" are visible by default:
$("div.newsinfo:not(.jopen)").hide();
If they're all hidden by default:
$("div.newsinfo.jopen").show();

Categories