brunodd
brunodd

Reputation: 2584

jQuery - onClick check if other div with same class is visible and hide it

I have the Show content button and need to show a div with the class tip when user clicks on it. How can I check if other divs using the same class are visible and if so hide them?

jsFiddle

$('.js-help-content').hide();

$('.js-show-help').click(function(e){
    e.stopPropagation();
    $('.js-help-content').fadeToggle(200);
});
$('.js-help-content').click(function(e){
    e.stopPropagation();
});
$(document).click(function(){
     $('.js-help-content').fadeOut(200);
});

Upvotes: 0

Views: 1064

Answers (2)

Shayan Salehian
Shayan Salehian

Reputation: 149

Add this line to your button onclick function:

$('.tip:visible:not(.js-help-content)').hide();

It has no effect on your js-help-content class which you are toggling, and also hides every other visible tip class.

Like this:

$('.js-show-help').click(function(e){
    e.stopPropagation();
    $('.tip:visible:not(.js-help-content)').hide();
    $('.js-help-content').fadeToggle(200);
});

Upvotes: 1

PeterKA
PeterKA

Reputation: 24638

Try this:

$('.tip:visible').not(this).hide();

$('.js-help-content').click(function(e){
    e.stopPropagation();
    $('.tip:visible').not(this).hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="js-show-help">Show content</p>

<div class="located-content tip js-help-content">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Beatae dolore ad, laboriosam sequi quia doloremque atque ex culpa aperiam ut.</p>
</div>

<div class="tip">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nostrum repudiandae, sequi mollitia inventore provident impedit numquam molestiae culpa dolorem minima odit quod nemo facilis voluptate esse quis voluptatem velit, architecto iusto dolorum praesentium! Vel deserunt quod ad, quas aliquid rerum.</p>
</div>

Upvotes: 0

Related Questions