Switching between two different classes jQuery - javascript

Having trouble getting the following code to work:
$('#changeMode').button().click(function(){
$('#playfield').toggle(function() {
$(this).switchClass("gridView","plainView");
}, function() {
$(this).switchClass("plainView","gridView");
});
});
I cannot get it to switch the following div's class.
<div id="playfield" class="gridView"></div>
Any ideas?
EDIT: I tried this:
$('#changeMode').button().click(function(){
if ($('#playfield').attr('class') == "gridView"){
$('#playfield').removeClass("gridView");
$('#playfield').addClass("plainView");
} else {
$('#playfield').removeClass("plainView");
$('#playfield').addClass("gridView");
}
});
And it seems to work fine, what the heck?

I wasn't aware of a switchClass, perhaps you were thinking of toggleClass? Anyways - I had some old code that used this (I was having some strange issues with toggleClass):
$(this).removeClass("gridView").addClass("plainView");
or
$(this).toggleClass("gridView plainView");
and vice versa.
Example:
$('#changeMode').button().click(function(){
$('#playfield').toggle(function() {
$(this).toggleClass("gridView plainView");
//$(this).removeClass("gridView").addClass("plainView");
}, function() {
$(this).toggleClass("plainView gridView");
//$(this).removeClass("plainView").addClass("gridView");
});
});
But as others have suggested toggleClass should work for your needs.

The correct syntax is to use "One or more class names (separated by spaces).." ( from .toggleClass()) within the first parameter, rather than quoting classnames in the first and second parameter.
e.g.
$(this).toggleClass("gridView plainView");

just use the toggleClass twice will do the magic . toggoleClass refference to Jquery
This method takes one or more class names as its parameter. In the first version, if an element in the matched set of elements already has the class, then it is removed; if an element does not have the class, then it is added.
as for ur problem .
$('#changeMode').button().click(function(){
$(this).toggleClass('gridView').toggleClass('plainView');
});
help this will solve ur problem .
#Guy toggleClass('gridView plainView') this will actually be alternates bettween
<div class="gridView plainView"> and <div class=" ">. and not toggle bettween the two classe . no offence . hope this will do some help .

jQuery also has a toggleClass API:
http://api.jquery.com/toggleClass/
This works just like what Rionmonster suggested, adding classes when they aren't set on the class and removing them when they are already set.

Related

JS IE8, 7, 9 Error 'attr(..)' is null or not an object

I want to show the box-shadow when div is expanded. I am adding a class which is having a box-shadow class in expanding div case.
And it is working fine in all the browsers.
Problem what I am facing is IE 8 is showing an error :- 'attr(...)' is null or not an object.
I need your help to fix this. Please suggest.
This is what I have done:
<script type="text/javascript">
animatedcollapse.addDiv('navDrop', 'fade=0,speed=100,')
animatedcollapse.addDiv('needHelp', 'fade=10,speed=300,')
animatedcollapse.ontoggle=function($, divobj, state){ //fires each time a DIV is expanded/contracted
//$: Access to jQuery
//divobj: DOM reference to DIV being expanded/ collapsed. Use "divobj.id" to get its ID
//state: "block" or "none", depending on state
jkmegamenu.render($);
if($(".needHelpBox").attr('class').indexOf("shadow") > 0)
{
$(".needHelpBox").attr('class',$(".needHelpBox").attr('class').replace("shadow",""));
}
else
{
$(".needHelpBox").addClass('shadow');
}
}
animatedcollapse.init()
</script>
Please help..!
Thanks
You're using jQuery! Use the methods that are here for you:
var helpBox = $(".needHelpBox");
if(helpBox.hasClass('shadow')){
helpBox.removeClass('shadow');
} else {
helpBox.addClass('shadow');
}
Bergi's solution is even simpler as it takes advantage of the toggleClass method.
The problem you're facing might also be within the selector $(".needHelpBox")
Are you sure the html element has the right class (needHelpBox) attribute?
And what version of jQuery are you using?
It seems you want to use the toggleClass() method (if you use jQuery):
$(".needHelpBox").toggleClass("shadow");
or the toggleClassName method (you use Prototype, which seems likelier when there is no attr):
$(".needHelpBox").toggleClassName("shadow");

Use duplicate class name on an element?

I found that there are many frameworks that will check the duplicate class name before adding the new class name on the element which I think will slow down the performance.
Are there any problems when the element has a duplicate class name?
It will also apply the CSS class without conflict while the duplicate class name is in use.
<div class="aa bb cc aa"></div>
Is it OK to add a class name simply just like elem.className += ' ' + 'aa ee', even if the element has a duplicate class name?
There is nothing "wrong" with having a duplicate class name, it's just redundant. There's probably a small performance impact, but that'll only really make much difference if you have a lot of duplication.
Also, preventing duplicates just helps to keep things tidy.
Semantic UI heavily uses attribute selectors
like here
.ui.grid [class*="left floated"].column {
margin-right: auto;
}
.ui.grid [class*="right floated"].column {
margin-left: auto;
}
If you want margin-left and margin-right to have the auto value, you must have a duplicate of the classname segment floated (ex. <div class="left floated right floated">Lorem</div>)
The DOM-API provides a convenient way for adding and removing and testing class-names of DOM-elements: classList.add(name) and classList.remove(name) and classList.contains(name).
In the ES6 context the question could perhaps be rephrased as:
"If I use .classList.add() to add the same className more than once, and then want to remove that class with classList.remove(), do I need to call classList.remove() multiple times?
Luckily the answer seems to be a single call to .classList.remove() is enough to remove a given class no matter how many times you have added it.
I couldn't find an easy answer to this by Google so I wrote the following test to tell me that is how it behaves. Calling the below function with DOM-element as argument does NOT throw an error:
function testClassListRemove (dem)
{
dem.classList.add ("hello");
dem.classList.add ("hello");
dem.classList.add ("hello");
ok (dem.classList.contains ("hello") );
dem.classList.remove ("hello");
ok (! dem.classList.contains ("hello") );
function ok (b)
{ if (! b)
{ throw new Error ('not ok ');
}
}
}

Using javascript to insert id into list elements

I am messing around with a deck of cards that I made.I have it set up so that there is a method that spits out cards by suit into a list, so if I want spades I get a <ol> of all of the spades cards. I am now trying to give each <li> element an id depending on what card it is. ace will be <li id="ace"><img src="ace_spades.gif"/></li> king will be <li id="king"><img src="king_spades.gif"/></li> for example.The list is in order from top to bottom akqj1098765432 . I tried doing this:
var card_id=["ace","king","queen","jack","ten","nine","eight","seven","six","five","four", "three","two"];
var counter=0;
while (counter<=12)
{
$(document).ready(function(){
$("li").eq(counter).attr("id", card_id[counter])
});
counter++;
}
but it doesn't work. I have not really done anything with javascript before besides simple jquery stuff. What am I getting wrong here?
Try this:
$(document).ready(function(){
var card_id = ["ace","king","queen","jack","ten","nine","eight","seven","six","five","four", "three","two"];
$.each(card_id, function(i,id){
$("li").eq(i).attr('id',id);
});
});
You should try to only have one $(document).ready() function and it's not necessary to use a while() loop.
I think you don't need to call $(document).ready() function in the while. Try this:
var card_id=["ace","king","queen","jack","ten","nine","eight","seven","six","five","four", "three","two"];
var counter=0;
while (counter<=12){
$("li").eq(counter).attr("id", card_id[counter]);
counter++;
}
You do not need the document ready function. Place your script just before </body> and after the jquery.js script. This is working for me.
Check working example at http://jsfiddle.net/H8MeG/2/
First of ID's in a webpage have to be unique. Some browsers might ignore id's of elements that have already been used. Other browsers might fail completely...
Second off. you shouldn't use .eq() like that.
You definitely shouldn't add 12 new $(document).ready() statements.
Here's a more reliable version and the example on jsfiddle
var card_id=["ace","king","queen","jack","ten","nine","eight","seven","six","five","four", "three","two"];
$("#spades li").each(function(index){
$(this).attr("class", card_id[index]);
$(this).text(card_id[index]);
});
I also added $(this).text(card_id[index]); so you see it actually works. Try to uses classes for multiple elements that share the same characteristic.
why are you messing with ids at all?
you know that the first item is the ace, the second the king, and so on.
ol.getElementsByTagName('li')[12]='deuce'

Can I remove just the last added class from an element with jQuery

Hey guys, the question pretty much asks itself... however, for more clarity:
I have an element called "chuckPalahniuk" and it has classes named "choke", "fightclub" and "haunted".
How could I get it so when I click on the "chuckPalahniuk" element, it removes "haunted" first, then "fightclub" on the second click and "choke" on the third?
also: be aware that the class names are dynamically added.
Cheers. peeeps!
psy.example:
$('#chuckPalahniuk').click(function() {
$(this).removeLastClassAdded(); //except this function doesn't exist...
});
just save in an array variable c every class you add c.push('yourclass'), then $(this).removeClass(c.pop());
http://www.devguru.com/technologies/ecmascript/quickref/pop.html
This will do it and will deal with leading and trailing whitespace, which a split()-based solution will not:
$('#chuckPalahniuk').click(function() {
this.className = this.className.replace(/(^|\s+)[^\s]+(\s+)?$/, "");
});
Something like:
$('#chuckPalahniuk').click(function() {
$(this).removeClass($(this).attr('class').split(/\s+/).pop());
});

Toggle effect problem when using for-loop in IE7

I'm a webdesigner that's trying to get the hang of JavaScript and jQuery, and I want to learn how to write shorter, more concise code - to avoid being ridiculed by the developers at work ;)
I have this snippet:
// toggle divs when checkbox is checked
$('.product-optional-checkbox1').click(function () {
$('.product-optional-toggle1').toggle('fast');
});
$('.product-optional-checkbox2').click(function () {
$('.product-optional-toggle2').toggle('fast');
});
$('.product-optional-checkbox3').click(function () {
$('.product-optional-toggle3').toggle('fast');
});
// hide divs
$('.product-optional-toggle1').hide();
$('.product-optional-toggle2').hide();
$('.product-optional-toggle3').hide();
...that I want to reduce using a for-loop, like this:
for( var i = 1; i < 4; ++i ) {
$('.product-optional-checkbox' + i).click(function () {
$(this).parent('div').find('div').toggle('fast');
});
$('.product-optional-toggle' + i).css({ display: 'none'});
};
It works fine in FF, however in IE7 it toggles twice. Anyone know who to solve a problem like this?
It's hard to say without seeing the HTML structure but maybe going to the parent then descendants is finding multiple divs?
In your example, you could replace:
$(this).parent('div').find('div').toggle('fast');
With code more similar to the original examples:
$('.product-optional-toggle' + i).toggle('fast');
However, it would be much better to ditch all the numbers and just use a class of .product-optional-checkbox. This way you can add a click function to all elements of that class in one go and avoid the loop:
$('.product-optional-checkbox').click(function () {
// do stuff using $(this)
});
Given that your click events seem to be tied to checkboxes (based on the class names you have in your example), why not actually provide code to handle click events for those checkboxes? For example:
<div id='my_group_of_checkboxes'>
<input type="checkbox" id="checkbox1">
<input type="checkbox" id="checkbox2">
...
</div>
And your jQuery code is then stripped down to three lines:
$('#my_group_of_checkboxes :checkbox').click(function(){
$(this).parent('div').hide('fast');
});
You also seem to need to hide the <div> elements related to each checkbox:
$('div[class^="product-optional"]').hide();
Although ID selectors would be a better option here and, depending on their position within your page, you may even be able to get away with something like:
$('#my_container_div_id div').hide();
If you can post some of your HTML, that might help provide more accurate answers as well.

Categories

Resources