1

I've got the functionality that allows you to open and close the hidden dropdown that you can see in the link but I want to also be able to close the already open dropdown if you click the same image again.

At the moment I can only close the ones on the outside of the clicked element.

Main fragment of code (wired up on ready), complete working sample - JsFiddle:

function close() {
    $('.slide').removeClass("active");
    $('.slide').css("padding-bottom", 0 + "px");
} 

function open() {
    $(this).addClass("active");
    $(this).css("padding-bottom", height);
} 

$('.slide').on('touchstart click', function() {

    close();

    if ( $(this).hasClass("active") ) {
        close();
    } 

    if ( !$(this).hasClass("active") ) {
        $(this).addClass("active");
        $(this).css("padding-bottom", height);
    }
});  

HTML:

 <div class="slide"> title 
      <div class="js-slide">content of slide  hidden via CSS when 
        "active" class is not present</div>
 </div>
3
  • jsfiddle.net/960cm7ux Commented May 16, 2015 at 19:54
  • not allowing me to add this link for some reason, sorry I've added it here Commented May 16, 2015 at 19:54
  • Inlined sample... removed thank you note... Commented May 17, 2015 at 18:56

1 Answer 1

1

This change to your code seems to achieve the desired effect:

$('.slide').on('touchstart click', function() {

    if ( $(this).hasClass("active") ) {
        close();
    } else {
        close();
        $(this).addClass("active");
        $(this).css("padding-bottom", height);
    }
});  

Because your close() function removes the active class from the element, you need to have it in a place where it won't mess with the conditions your checking around the active class. Moving it inside the if blocks is an easy and quick change to fix the issue. Some people might be bothered by the way close() is repeated in both blocks. If you're one of those people, refactor appropriately. Just don't do the obvious-seeming move close() outside the if/then because that will cause this issue to re-appear.

Fiddle: https://jsfiddle.net/960cm7ux/1/

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

1 Comment

ah awesommeee... i get it.. so basically what i was doing is always ending up with an open dropdown.. where as this closes it unless it doesn't have the class active..

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.