Search code examples
javascriptjqueryalertfadeinfadeout

I want to fadein a div onclick and fadeout div after a certain time automatically


Actually my problem is, I want to fadein a div on click event, and fadeout that div after a certain time automatically.

I have made some thing, but the fadeout function is not working. Here is my snippet:

.alert-box {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  display: none;
  padding: 20px 0;
  background-color: red;
  color: #fff;
}

.close {
  position: absolute;
  right: 10px;
  top: 10px;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<button>click me</button>


<div class="alert-box">
  <span class="close">&times;</span>
  <div class="content">
    sample content
  </div>
</div>


<script type="text/javascript">
  $(document).ready(function() {
    $('button').click(function() {
      $('.alert-box').fadeIn('fast');
    });
    if ($('.alert-box').css('display') == 'block') {
      $('.alert-box').delay(1000).fadeOut('fast');
    }
  });
</script>


Solution

  • Use setTimeout for fadeout after 1 second

    setTimeout (() => {
        $('.alert-box').fadeOut('fast');
    }, 1000)
    

    Removed the unnecesary code too.

    .alert-box {
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      width: 100%;
      display: none;
      padding: 20px 0;
      background-color: red;
      color: #fff;
    }
    
    .close {
      position: absolute;
      right: 10px;
      top: 10px;
      cursor: pointer;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button>click me</button>
    
    
    <div class="alert-box">
      <span class="close">&times;</span>
      <div class="content">
        sample content
      </div>
    </div>
    
    
    <script type="text/javascript">
      $(document).ready(function() {
        $('button').click(function() {
          $('.alert-box').fadeIn('fast');
          setTimeout(() => {
            if ($('.alert-box').css('display') == 'block') {
              $('.alert-box').delay(1000).fadeOut('fast');
            }
          }, 1000);
        });
    
      });
    </script>