-1

I know there's a simple way to do it, but I;m still new to js. I just need to toggle between these two classes and wouldn't know the function. Here's the markup:

HTML Example

JQUERY

<script type=”text/javascript”>
$(document).ready(function() {
$( ".item" ).click(function() {
$( ".itemcontent" ).toggleclass();
});
});
</script>

2 Answers2

1

If '.item' elements having the class '.itemcontent' need to toggle this latter one upon click

$( ".item" ).click(function() {
    $(this).toggleClass('itemcontent');
});
Stphane
  • 3,368
  • 5
  • 32
  • 47
0

The 'toggleClass' function will add or remove a single class.

So $('.item').toggleClass('itemcontent') will either add or remove the 'itemcontent' class to all of the elements with a class of item. If you call toggleClass('itemcontent') many times, you'll remove the class itemcontent, then add the class, then remove it, and so on.

If you need to toggle between two classes, you need to send two classes to the toggleClass call.

Like this:

$('.item').toggleClass('class1 class2')

This would toggle between class1 and class2 assuming that the element stated with one and not the other.

So if you want class item to toggle between class1 and class2 your code should be:

$( ".item" ).click(function() {
    $(this).toggleClass('class1 class2');
});

Remember that elements can have multiple classes at the same time. To start, your item should have either class1 or class2. Then, the item will toggle between the two classes. If you item has neither class1 nor class2 to start, it will just turn on and off both classes at the same time.

Damien Black
  • 5,579
  • 18
  • 24