How to display auto fade out message using jQuery

Sometimes we need to display a message and then fade it out. jQuery fadeOut will make an element fadeOut (by animating css property opacity) will make its css property display to none eventually. Here is sample code for it.

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

<input type="button" id="id1" type="button" value="click me">
<span style="color:red;" id="fademsg"></span>

<script type="text/javascript">
$("#id1").click(function () {
  $("#fademsg").text("A message that will fadeout");
  $("#fademsg").fadeOut(3000);
});
</script>
refresh

Note that we had to set the display to inline (anything other than none, so that the example can work on 2nd and subsequent clicks also.

Fadeout messaged displayed at top center

We can also make fade out message at fixed position and place it at the top and center of the window.
jquery-fadeout-message-top-center-example

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

<input type="button" id="id1" type="button" value="click me">
<span style="color:red;" id="fademsg"></span>

<script type="text/javascript">
$("#id1").click(function () {
  $("#fademsg").css("display", "none");
  $("#fademsg").text("A message that will fadeout");
  $("#fademsg").css("position", "fixed");
  $("#fademsg").css("left", "50%");
  $("#fademsg").css("top", "0px");
  var w = parseInt($("#fademsg").css("width"), 10);
  $("#fademsg").css("margin-left", "-" + w/2 + "px");
  $("#fademsg").css("display", "inline");
  $("#fademsg").fadeOut(3000);
});
</script>
refresh

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments