Joseph Mueller
Joseph Mueller

Reputation: 1

Click only when parent hasclass

I'm a novice in the front end department. I am trying to have a div only be clickable if its parent has a certain class applied to it. Here is my current code.

if( !$('#capstone').closest().hasClass('slick-active') ){


 $('#capstone').click(function(e){    
    $('#capstone-container').fadeIn('slow');
 });


$('#capstone-close').click(function(e){    
   $('#capstone-container').fadeOut('slow');

});

}

The problem here is the child div "#capstone remains clickable even when its parent does not have the class "slick-active" applied to it.

Upvotes: 0

Views: 74

Answers (1)

Oriol
Oriol

Reputation: 288100

Once you add an event listener, it won't be removed in case the condition you checked to add it becomes false.

Instead, you can remove it manually when you change the class.

Alternatively, you can check your condition inside the event handler:

var $capstone = $('#capstone'),
    $capstoneContainer = $('#capstone-container');
function condition() {
    return !$capstone.closest().hasClass('slick-active');
}
$capstone.on('click', function(e){    
    if(condition()) $capstoneContainer.fadeIn('slow');
});
$('#capstone-close').on('click', function(e){    
   if(condition()) $capstoneContainer.fadeOut('slow');
});

Upvotes: 1

Related Questions