2

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.

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I almost thought that could be the problem, though I did not have the words (or technical knowledge) to describe it. Thank you for your help!
No problem @sdny. I just added more some more info in case you want to actively bind events.
You're right. I don't need two states. I guess the first version is never the most elegant one. I haven't used .on() before, but I will look into it now.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.