Theodore Steiner
Theodore Steiner

Reputation: 1605

Animation onClick - Jquery

This may be a silly question but if you have a function that onClick makes a modal appear by moving from display: none to display: block, is it possible to animate only one portion of the transition. What I mean by that is can you have it appear "instantly" when it is display:block and then fade-out as it is taken off screen?

See snippet example below

$(function(){
  $('.square').click(function() {
    $('.modal').toggleClass('showModal');
  });
});
.square {
  height: 50px;
  width: 50px;
  border: 1px solid;
  content: '';
}

.modal {
  height: 400px;
  width: 400px;
  background-color: #f1f1f1;
  display: none;
}

.showModal {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="square"></div>
<div class="modal"></div>

Upvotes: 0

Views: 2839

Answers (2)

Dan Kreiger
Dan Kreiger

Reputation: 5516

There might be an even more graceful way, but I wouldn't use the .showModal class to do this.

You can check if the element is set to display: none;

  • If so, you can change the element's css to display: block;
  • Else, you can use the jQuery fadeOut() method, which sets the css display: none by design.

Try the following snippet:

$(function(){
  $('.square').click(function() {
    if($('.modal').css('display') === 'none'){
     $('.modal').css('display', 'block');
    } else {
     $('.modal').fadeOut();
    }
  });
});
.square {
  height: 50px;
  width: 50px;
  border: 1px solid;
  content: '';
}

.modal {
  height: 400px;
  width: 400px;
  background-color: #f1f1f1;
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="square"></div>
<div class="modal"></div>

Upvotes: 1

Justinas
Justinas

Reputation: 43441

Yes, you can. Simply check if it's currently shown. If yes - use animation. If no - instant action.

$(document).ready(function() {
  $('button').click(function() {
    if ($('#div').hasClass('active')) {
      $('#div').slideUp(function() {
        $('#div').removeClass('active').show();
      });
    } else {
      $('#div').addClass('active');
    }
  })
})
#div {
  height: 0;
  background-color: blue;
}

#div.active {
  height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Toggle</button>
<div id="div"></div>

Upvotes: 1

Related Questions