brunodd
brunodd

Reputation: 2584

Jquery: Show related div when you click and hide others

I have 2 divs with different content. I want to show the related div when I click on the link. It's showing both divs at the moment and it was supposed to show only the related one.

jsfiddle

$('div.tip-2').hide(); 

$('.showDiv').on('click', function() {
    $('div.tip-2').fadeIn(200);
    event.stopPropagation();
});

$(document).click(function(e) {
    if (!$(e.target).is('div.tip-2 *')) {
        $("div.tip-2").fadeOut(200);
    }
});

HTML

<a class="showDiv" href="#">Show div</a>
<div class="tip-2">
<p>This is one!</p>
</div>

<br/><br/>
<a class="showDiv" href="#">Show div</a>
<div class="tip-2">
<p>This is two!</p>
</div>

Upvotes: 0

Views: 127

Answers (3)

Rino Raj
Rino Raj

Reputation: 6264

Please try this:

    $('div.tip-2').hide(); 

    $('.showDiv').on('click', function() {
       $("div.tip-2").hide();
       $(this).next('.tip-2').fadeIn(200);
       event.stopPropagation();
    });

    $(document).click(function(e) {
        if (!$(e.target).is('div.tip-2 *')) {
            $("div.tip-2").fadeOut(200);
        }
    });

http://jsfiddle.net/Rino_Raj/g25hsdw6/5/

Upvotes: 1

Balachandran
Balachandran

Reputation: 9637

Try this

$('div.tip-2').hide(); 

$('.showDiv').on('click', function() {
    $("div.tip-2").hide();
    $(this).next().fadeIn(200);
    event.stopPropagation();
});

$(document).click(function(e) {
    if (!$(e.target).is('div.tip-2 *')) {
        $("div.tip-2").fadeOut(200);
    }
});

updated Fiddle

Upvotes: 1

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167192

Make the script understand its relation. Change it to:

$('div.tip-2').hide(); 

$('.showDiv').on('click', function() {
    $this = $(this);
    $('div.tip-2').fadeOut(200, function () {
        $this.next('div.tip-2').fadeIn(200);
    });
    event.stopPropagation();
});

$(document).click(function(e) {
    if (!$(e.target).is('div.tip-2 *')) {
        $("div.tip-2").fadeOut(200);
    }
});

Fiddle: http://jsfiddle.net/praveenscience/g25hsdw6/4/

Upvotes: 2

Related Questions