I have the following JS which sets a background class. However, is it possible to remove the previous set class?
I cannot remove them all as it contains other classes so just whatever is set from that on mouseover function or maybe if that's not possible removing wildcard class?
Classes being set all end with *-bean-bags so maybe we could do that but guess not that flexible.
Whats expected:
Hover item and set class
Hover another item and remove previous set class and set new class
Anyone have any ideas?
$('.ty-menu__submenu-list li').on("mouseover", function () {
var menuBackground = $(this).attr("data-background");
//console.log(menuBackground);
$("div.ty-menu__submenu.ty-menu__submenu-to-right").removeClass (function (index, css) {
return (css.match (/\b-bean-bags\S+/g) || []).join(' ');
});
$("div.ty-menu__submenu.ty-menu__submenu-to-right").addClass(menuBackground);
});
Store the class to remove in a custom attribute, like this:
$('.ty-menu__submenu-list li').on("mouseover", function () {
//Get the names of the new class
var menuNewBackground = $(this).attr("data-background");
//Get a reference to the element with the classes.
elm = $("div.ty-menu__submenu.ty-menu__submenu-to-right");
//Get the name of the old class
var menuOldBackground = elm.attr("data-background-old");
//First remove the old, add the new, and save the name of the new,
//so that it can be used to remove it later.
elm.removeClass(menuOldBackground)
.addClass(menuNewBackground)
.attr("data-background-old", menuNewBackground);
});
At the same time that you add the class to the parent div, add the same value to a data-prev-class (or whatever you wish to call it) attribute of the parent div. With it being in two places, you will be able to access it from a more variable like way.
Related
I have a navigation menu with about 10 items, and I put together this code to update the links for which is selected and which is not. It manually updates classes. The problem is, as you can probably tell, its inefficient and its a pain to update. Is there a better way of doing it?
$('#Button1').click(function(){
$('#Button1').addClass("selectedItem");
$('#Button2').removeClass("selectedItem");
$('#Button3').removeClass("selectedItem");
$('#Button4').removeClass("selectedItem");
$('#Button5').removeClass("selectedItem");
$('#Button6').removeClass("selectedItem");
$('#Button7').removeClass("selectedItem");
$('#Button8').removeClass("selectedItem");
$('#Button9').removeClass("selectedItem");
$('#Button10').removeClass("selectedItem");
});
You could try something like this -
$("[id^='Button']").removeClass("selectedItem");
$('#Button1').addClass("selectedItem");
This will first remove all the selectedItem classes from any element which has an id attribute starting with "button". The second command then adds the class to Button1
You could also simply bind all the elements with the same handler like this -
var $buttons = $("[id^='Button']");
$buttons.on('click', function ()
{
$buttons.removeClass("selectedItem");
$(this).addClass("selectedItem");
});
For each element, when clicked, the class will be removed - the element that was clicked with then have the class added.
Checkout the Attribute Starts With Selector [name^="value"] selector.
I would suggest using classes because this is exactly what they are for - to denote groups of elements. While you can easily select your buttons using the method proposed by Lix (and you should use this method if you can't modify HTML), using class is a more unobtrusive:
var $buttons = $('.button').on('click', function() {
$buttons.removeClass('selectedItem');
$(this).addClass('selectedItem');
});
Meta example: http://jsfiddle.net/88JR2/
You could have a class .button and apply it to all your buttons then
$('#Button1').click(function(){
$('.button').removeClass("selectedItem");
$('#Button1').addClass("selectedItem");
});
I am trying to add a class to a newly appended DIV without using something like:
t.y.append('<div class="lol'+i+'"></div>');
Here's a better example of what I'm trying to do:
var t = this;
$(this.x).each(function(i, obj) {
//append new div and add class too <div></div>
t.y.append('<div></div>').addClass('lol'+i);
});
Page load HTML looks like:
<div class=".slideButton0 .slideButton1 .slideButton2" id="sliderNav">
<div></div>
<div></div>
<div></div>
</div>
When you append an element through .append, it doesn't change the context of the jQuery object.
You could write it like this:
$('<div></div>').appendTo(t.y).addClass('lol'+i);
or
$('<div></div>').addClass('lol'+i).appendTo(t.y);
(these both do the same thing, simply in different orders, the second possibly being more clear)
the context of the jQuery object will be the newly created div.
t.y.append('<div></div>').addClass('lol'+i);
should be
t.y.append('<div></div>').find('div').addClass('lol'+i);
In the first case you are adding class to the div to which you are appending ..
SO the context is still the parent div and not the newly appended div..
You need to find it first inside the parent and then add the class..
EDIT
If you want to just add the class to the last appended element ... Find the last div in the parent and then add the class to it..
This will make sure you are not adding the class to all the div's every single time you iterate in the loop..
t.y.append('<div></div>').find('div:last').addClass('lol'+i);
Try this:
t.y.append($('<div></div>').addClass('lol'+i));
Fiddle: http://jsfiddle.net/gromer/QkTdq/
var t = this;
$(this.x).each(function(i, obj) {
//append new div and add class too <div></div>
var d = $('<div />').addClass('lol' + i);
t.y.append(d);
});
The problem is that append returns the container instead of the thing you just appended to it. I would just do the addClass before the append instead of after:
var t = this;
$(this.x).each(function(i, obj) {
//append new div and add class too <div></div>
t.y.append($('<div></div>').addClass('lol'+i));
});
EDIT ... or, in other words, exactly what Gromer said. Beat me by five whole minutes, too. I'm getting slow.
You don't mention why you want to number the class attribute to your list items, but in the case that you are actually using them for css don't forget you have :odd and :even css selector attritbutes and also the equivalent odd/even jQuery selectors.
http://www.w3.org/Style/Examples/007/evenodd.en.html
http://api.jquery.com/odd-selector/
I didn't find anything like this. notice the class attribute!
$.each(obj, function (_index, item) {
resultContainer.append($('<li>', {
class: "list-group-item",
value: item.id,
text: item.permitHolderName || item.permitHolderId
}));
});
I'm looking to change the class (hide) of certain div's dependent on their attribute values.Here's my code, it might make a bit more sense once you've seen this:
jQuery('#menu1').click(function() {
jQuery([.attr('imageref')]!=[.attr('menuref')]).removeClass('pics').addClass('.pics-hidden').removeClass('pics').fadeOut(200);
jQuery('#projectimages').masonry('reload');
});
So what I'm after is that if you click on #menu1 it will remove .pics with the same imageref attribute as the #menu1 atrribute menuref.
So clicking on #menu1 which has menuref equal to 1, will hide the relevant .pics with an imageref also equal to 1.Hopefully that makes sense, any help would be greatly appreciated!
You can use the css selectors to make this.
ie:
jQuery('#menu1').click(function()
{
jQuery('[imgeref="menuref"]').removeClass('pics').addClass('pics-hidden');
});
edit:
this will search all the elements wich his atribute 'imageref' is set to 'menuref' and then remove the class pics and add the class pics-hidden.
if it's only necesary to img tags. then you could change:
jQuery('[imgeref="menuref"]')
to
jQuery('img[imgeref="menuref"]')
You might use the jQuery filter function.
http://api.jquery.com/filter/
Description: Reduce the set of matched elements to those that match the selector or pass the function's test.
var menuref = ("#menu1").attr('menuref')
// Get all pics with an imageref attribute
jQuery(".pics[imageref]")
// Filter them
.filter(function(){
return $(this).attr('imageref') != menuref;
})
// Do what ever you want e.g. remove the pics class
.removeClass('pics')
You use the attribute-equals selector, and concatenate into the selector the value of the menuref attribute.
jQuery('#menu1').click(function() {
var menu = $(this).attr('menuref');
jQuery(".pics[imageref='" + menu + "']").toggleClass('pics pics-hidden')
.fadeOut(200);
jQuery('#projectimages').masonry('reload');
});
I feel like this is a stupid simple question, but I've been doing so much CSS work lately that I feel a little rusty. So, I have several buttons with classname: and class: attributes. Basically, all I want to do is take the value of the classname attribute and append it to class. Only the buttons with className need their content appended.
classname="blah_btn blah_btnGrey" class="blah blah blah foo foo"
Would I write something like:
if ($('#ui-button').has("className")) {
$(("className").val()).appendTo("class");
or something more along the lines of:
$("button").each(function() {
//do stuff
});
Or am I in the completely wrong ballpark? Once again, any help is greatly appreciated.
First off, please don't use an attribute call className. That is reserved as the way to address the class attribute because class is a reserved word in javascript. So, if you use attributes with names of class and className, you could end up having a hard time reaching them individually in javascript. It could be a mess. Pick a more unique name for the one that isn't actually class.
To add the class attribute, you would just use .addClass():
$('#ui-button').addClass("blah_btn")
jQuery's `addClass() is smart enough to not add it if it's already present.
If you want to get an attribute and add it to the actual class, you can do this:
$('#ui-button').addClass($(elem).attr("myAttribute"));
If you just want to add one attribute onto another, you can do this:
var target = $('#ui-button');
target.attr(target.attr("myAttribute") + $(elem).attr("myAttribute"));
That's what you need ?
$.each($('#ui-button.className'), function() {
var $element = $(this);
$element.addClass($element.val());
});
How about this?
$('button[className]').each(function(){
var classNameValue = $(this).attr('className');
var classValue = $(this).attr('class');
$(this).attr('class', classValue + classNameValue);
});
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"]);