Search code examples
jqueryshow-hidemessagebox

jQuery - Show simple message box when clicked?


How to show message box and close it when clicked an element using jQuery?
It is something like to show a success message when clicked a button.


Solution

  • HTML, CSS, JS:
    (The message box will be shown on top of the cursor and aligned at the center.)

    $("body").append("<div class=\"msg\">Message to be shown</div>");
    $('button.msg').on('click', function(e) {
      $("div.msg").finish();
      $("div.msg").css({
        "top" : e.pageY - $("div.msg").outerHeight() - 2,
        "left" : e.pageX - $("div.msg").outerWidth() / 2
      });
      $("div.msg").show();
      $("div.msg").fadeOut(1000, 'easeInOutQuart');
    });
    body {
      margin: 75px;
    }
    
    div.msg {
      position: absolute;
      border: 1px solid black;
      background-color: white;
      text-align: center;
      vertical-align: middle;
      display: none;
      top: 0;
      left: 0;
      pointer-events: none;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.0/jquery-ui.min.js"></script>
    <button class='msg'>Click me</button>

    It is recommended to append the message(div.msg) to body.