sdny
sdny

Reputation: 156

jQuery remove own class on click

Weird question:

I am in the process of creating a simple, CSS3-animated slideout panel. The animations are triggered using jQuery. I have two versions, one that works, and one that doesn't.

FIDDLE to the working version.

Code of the dysfunctional version:

$('.mark').click(function () {
    $('.box').addClass('box-up');
    $('.box').removeClass('box-down');
    $(this).addClass('active');
    $(this).removeClass('inactive');
});
$('.active').click(function () {
    $('.box').addClass('box-down');
    $('.box').removeClass('box-up');
    $(this).addClass('inactive');
    $(this).removeClass('active');
});

This is the jQuery I would like to work, unfortunately it doesn't. The intended result of the second version is to allow the user to click the <div class="mark"></div> to open and close the slideout panel.

What am I doing wrong? Any help would be greatly appreciated.

Upvotes: 2

Views: 792

Answers (2)

2pha
2pha

Reputation: 10155

Try this one.
http://jsfiddle.net/JNyzP/2/

Ignore the stuff below
Damn...I need 30 chracters to post....
And jfiddle link needs code attached to comment

//code goes here

Upvotes: 1

Paul Sham
Paul Sham

Reputation: 3205

jQuery will bind events when the page loads. It does not actively look for elements to binds events to. So, in your example, when the page loads, jQuery will look for $('.active') and will find none.

Instead, what you can do is bind one click event to $('.mark') and have an if statement that checks whether it is active.

$('.mark').click(function () {

  // check if mark is inactive
  if($(this).hasClass('inactive'){
    $('.box').addClass('box-up');
    $('.box').removeClass('box-down');
    $(this).addClass('active');
    $(this).removeClass('inactive');
  }

  // check if mark is active
  else if($(this).hasClass('active'){
    $('.box').addClass('box-down');
    $('.box').removeClass('box-up');
    $(this).addClass('inactive');
    $(this).removeClass('active');
  }

});

If you would like to actively bind events, look into using .on() with a selector of .active.

$('.box').on('click', '.active', function () { /* code here */ });

Side note:

I think it's redundant to have a both an up/down and active/inactive state. You could have the element with no class be closed and add a class be open, or vice versa.

Upvotes: 2

Related Questions