Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

javascript - Fade out old flash message before fading in new one?

I am new to jquery. I have a form which performs a calculation, and returns the result in a flash message. My goal behavior is:

  1. upon first form submit, flash message containing results fades in
  2. on subsequent submissions, the flash message containing the old results fades out, and then the new flash message fades in.

I am confused how to do this because obviously both the old and the new results have the same id.

Currently only the fade in is working.

jquery:

$(function() {
  $(".btn-primary").click(function() {
    $("#diagnosis").fadeOut("slow");
  });
$('#diagnosis').delay(0).fadeIn('normal', function() {
  $(this).delay(2500);
  });
});

CSS

#diagnosis { display:none; }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can chain fadeIn and fadeOut animations in Jquery. Note that you can also pass a complete function to either animation, such as $('#result').fadeOut('fast', () => {}). This ensures we only update the result when it fully disappears, then the new result will immediately fade in with the updated value. See more reference here.

let arr = [4, 5, 6, 7, 8, 9, 10]

$('form').on("submit", (e) => {
  e.preventDefault();
  
  // mock calculated result 
  let genIdx = Math.floor(Math.random() * 7);
  let resultVal = arr[genIdx];
 
  $('#result').fadeOut('fast', () => {
      $('#result').text(resultVal);
  }).fadeIn('fast');

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
  <body>
    <form>
      <p id="result"></p>
      <button type="subimit">Submit</button>
    </form>
  </body>
</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...