efficient
efficient

Reputation: 93

How to remove class with this JS function

This function is set up so it simply finds the -a's- within the class of menu-option-set, and says, upon click, add the class "selected" and remove the class "selected" from all others within that list.

What I want to do is simply have it so if you click the item that already has the class of "selected" then it removes the class of "selected". I know it shouldn't be "return false;" I just have that as a placeholder because I can't figure out the proper coding.

Thanks guys! :)

var $optionSets = $('.menu-option-set'),
    $optionLinks = $optionSets.find('a');

$optionLinks.click(function() {
    var $this = $(this);

    // Remove Class if already selected --> this is the part that I need help with
    if ($this.hasClass('selected')) {
        return false;
    }

    var $optionSet = $this.parents('.menu-option-set');
    $optionSet.find('.selected').removeClass('selected');
    $this.addClass('selected');
});​

Upvotes: 0

Views: 313

Answers (4)

rkw
rkw

Reputation: 7297

If you want to be concise:

$('.menu-option-set a').click(function() {
    $(this).toggleClass('selected').siblings().removeClass('selected')​​;
});

Upvotes: 0

GregL
GregL

Reputation: 38131

Alternatively, use the toggleClass() method as follows:

var $optionSets = $('.menu-option-set'),
    $optionLinks = $optionSets.find('a');

$optionLinks.click(function() {
    var $this = $(this);

    var $optionSet = $this.parents('.menu-option-set');
    $optionSet.find('.selected').not(this).removeClass('selected');
    $this.toggleClass('selected');
});​

EDIT: Added the .not(this) to exclude the clicked <li> from having the class removed before it should.

Upvotes: 0

Paul Fleming
Paul Fleming

Reputation: 24526

$('.menu-option-set a').click(function()
{
    // if clicked item is selected then deselect it
    if ($(this).hasClass('selected'))
    {
        $(this).removeClass('selected');
    }

    // otherwise deselect all and select just this one
    else
    {
        $('.menu-option-set a').removeClass('selected');
        $(this).addClass('selected');
    }
});

Upvotes: 1

detaylor
detaylor

Reputation: 7280

You should just be able to use $().removeClass('selected') i.e.

  if ( $this.hasClass('selected') ) {
      $this.removeClass('selected');
  }

However, you are also adding the class again later so this should not really be necessary.

You could inline this by selecting all the .selected elements, removing this and removing the class.

$this
  .parents('.menu-option-set')
  .find('.selected')
  .not(this)
  .removeClass('selected');

$(this).addClass('selected');

Upvotes: 1

Related Questions