Trigger isn’t adopting an active class

Relevant Codepen

Intended functionality:

  • If you click a trigger, it’s corresponding element must display
  • If you click another trigger, that trigger’s element displays and the other closes
  • If you click the trigger whilst it is open, it simply closes the element

Current problem:

Right now, target elements that displays once the trigger is clicked adhere to the above requirements, but the trigger itself doesn’t seem to be adopting the “active” class. The trigger, when pressed, should turn red (meaning it has the “active” class).

The html:

<ul>
    <li>
         <span class="trigger" data-target-id="target-1">Trigger 1</span>
         <div id="target-1" class="target">Target to reveal when I press Trigger 1</div>
    </li>
    <li>
         <span class="trigger" data-target-id="target-2">Trigger 2</span>
         <div id="target-2" class="target">Target to reveal when I press Trigger 2</div>
    </li>
    <li>
         <span class="trigger" data-target-id="target-3">Trigger 3</span>
    </li>
</ul>

<div id="target-3" class="target">Target to reveal when I press Trigger 3</div>

And the jQuery:

var trigger = ".trigger";
var recipient = ".target";
var not_trigger = $(".trigger").not(this);

$(trigger).click(function(e) {
  e.stopPropagation();
  recipient = '#' + $(this).attr('data-target-id');
  var not_recipient = $(".target").not(recipient);

// This handles the trigger element      

  if($(trigger).hasClass("active")){
    $(not_trigger).removeClass("active");
  }else{
    $(this).addClass("active");
  }

// This disgracefully handles the recipient element 

  if($(".target").hasClass("open")){
    $(not_recipient).removeClass("open");
    TweenMax.to($(".target"), .3, {display:'none', y:'0%', autoAlpha:0});

    if($(recipient).hasClass("open")){
      $(recipient).removeClass("open");
      TweenMax.to(recipient, .3, {display:'none', y:'0%', autoAlpha:0});
    }else{
      $(recipient).addClass("open");
      TweenMax.to(recipient, .3, {display:'block', y:'100%', autoAlpha:1});
    }
  }else {
    $(recipient).addClass("open");
    TweenMax.to(recipient, .3, {display:'block', y:'100%', autoAlpha:1});
  }

});

Answer

The problem in the code that you pasted is that it will never go into the if block, as the element does not have the active class at the point when the click happens.

Replace

 if($(trigger).hasClass("active")){
    $(not_trigger).removeClass("active");
    $(this).toggleClass("active") ;
  }

with

$(trigger).not(this).removeClass("active");
$(this).toggleClass("active");

One way to make it work with the same code that you have is, to set any of the li.trigger to active in the HTML. But that would still not account for the self click.

jsBin Demo

Leave a Reply

Your email address will not be published. Required fields are marked *