David Pešava
David Pešava

Reputation: 15

jQuery - fadeOut the div with click outside , after fadeIn

I have got problem with fadeIn/fadeOut My target is to click on button that will FadeIn the div and that if I click outside the div, that div will FadeOut. But problem is when i use my code all events happen in same time, it means FadeIn and FadeOut after one click. How can I do that div will FadeOut in right moment?

<div class="col-xs-12 col-md-6 col-sm-6 portfolio_page__box" id="portfolio_page__item1">
  <div class="portfolio_page__button1" id="portfolio_page--item1_showup">
    <p>INFO</p>
  </div>
</div>
<div id="portfolio_page__item1_showup_table"></div>

jquery:

$(function() {
  $("#portfolio_page--item1_showup").click(function() {
    $("#portfolio_page__item1_showup_table").fadeIn("slow");
    $(".portfolio_page__box").fadeOut("slow");
  });
});

$(document).click(function() {    
  if (this.id != 'portfolio_page__item1_showup_table') {
    $("#portfolio_page__item1_showup_table").hide();
  }    
});

Upvotes: 1

Views: 1249

Answers (1)

cssyphus
cssyphus

Reputation: 40038

This might have something to do with event propagation (bubbling) - you can read about that. Your HTML is not complete so cannot provide a sample solution.

Basic solution is to use a variable and keep track of visibility state. Here is a rough example to play with:

var viz = false;
$(function() {
  $("#portfolio_page--item1_showup").click(function() {
    $("#portfolio_page__item1_showup_table").fadeIn("slow", function(){
        viz = true;
    });
    $(".portfolio_page__box").fadeOut("slow");
  });
});

$(document).click(function() {
  if (viz) {
    $("#portfolio_page__item1_showup_table").hide();
    viz = false;
  }
});
.btn{padding:10px;border:1px solid orange;}
#portfolio_page__item1_showup_table{display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div class="col-xs-12 col-md-6 col-sm-6 portfolio_page__box" id="portfolio_page__item1">
  <div class="portfolio_page__button1 btn" id="portfolio_page--item1_showup">
    <p>INFO</p>
  </div>
</div>
<div id="portfolio_page__item1_showup_table">
  <table>
    <tr><td>Cell 1</td><td>Cell 2</td></tr>
    <tr><td>Cell 3</td><td>Cell 4</td></tr>
  </table>
</div>

Upvotes: 2

Related Questions