adardesign
adardesign

Reputation: 35761

Toggle (click) and bind event (on document)

I have a button <a> that should toggle a drop-down Then it should also bind (once) a click event to the document that when clicked it should slide it up.

I started with this HTML and JS... Any suggestions how to make this work?

HTML

      <a class="a" href="#">continue shopping</a>
      <div class="b">
        <a href="#">continue 1</a>
        <a href="#">continue 2</a>
        <a href="#">continue 3</a>
        <a href="#">continue 4</a>
      </div>

JS

 $(".a").toggle(function(event){
   buttonEvent = $(event.target)
    $(this).addClass("open").next(".a").slideDown(500);

    $(document).one("click",function(e){
    if(!$(e.target).is(".a") && !buttonEvent.hasClass("b")){
        $(".b").slideUp(500)
     }  
  })

 },
 function(){
  $(this).removeClass("open").next(".continueShopCntnr").slideUp(500)
});

But it is still buggy.. when clicked on again on the continue shopping it doesn't do nothing

Upvotes: 0

Views: 2176

Answers (1)

Lindsay
Lindsay

Reputation: 856

Maybe this would work better... it closes any open ones on the document click.

EDIT: Actually tested this code (vs the previous answer) and it works as I understand the requirements.

$(".continueShop").toggle(
    function(){
      $(this).removeClass("open").next(".continueShopCntnr").slideUp(500)
    },
    function(){
        $(this).addClass("open").next(".continueShopCntnr").slideDown(500);

        $(document).one("click",function() {
           $(".continueShop.open").each(function() { 
               $(this).click();
           });
         });
     }
);

Upvotes: 1

Related Questions