dialogs

by Alexandru Gatea

HTML

<p>
	Click on any button to toggle it's dialog. Each of them has a different message, but the Exit time is set to 2.5 seconds for each. To close it earlier click on it!
</p>
<button data-toggle="dialog" title="I'm a dialog box!">Click me</button>
<button data-toggle="dialog" title="I'm here too!">Click me</button>
<button data-toggle="dialog" title="I'm self dismissable!">Click me</button>

SCSS

.dialog {
  position: fixed;
  top: 50px;
  right: 50px;
  display: inline-block;
  padding: 10px 20px;
  font-size: 16px;
  border-radius: 40px;
  border: 1px solid #4FC3F7;
  background: #03A9F4;
  color: #fff;
  animation: dialog 0.5s ease forwards;
	z-index: 10000;
  &.out {
    animation: dialog-out 0.5s ease forwards;
  }
}

@keyframes dialog {
  0% {
    transform: translateY(50px);
    opacity: 0;
  }
  100% {
    transform: translateY(0px);
    opacity: 1;
  }
}

@keyframes dialog-out {
  0% {
    transform: translateY(0px);
    opacity: 1;
  }
  100% {
    transform: translateY(-50px);
    opacity: 0;
  }
}

p {
	max-width: 450px;
	font-size: 14px;
	line-height: 1.6;
	margin-bottom: 30px;
	padding: 10px;
}

button {
	padding: 10px 20px;
	margin: 10px;
	border: #01579B;
	background: #039BE5;
	color: #fff;
	font-weight: bold;
	font-size: 16px;
	cursor: pointer;
}

JavaScript

// get dialog toggler btn
var dialogToggle = $('[data-toggle="dialog"]');

// set markup for dialog
var dialog = "<div class='dialog'></div>";

//set variables for timed animations 
var animateDialog, removeDialog;

// show dialog on button click
dialogToggle.on('click', function() {

  // clear timers to ensure propper timing upon new click
  clearTimeout(animateDialog);
  clearTimeout(removeDialog);

  // get text to be displayed on clicked dialog
  var text = $(this).attr('title');
  // remove any dialogs in the page
  $('body .dialog').addClass('out').remove();

  // append dialog markup to body 
  $('body').append(dialog);
  // find added dialog and add it's text
  $('.dialog').text(text);

  // set animation out timer
  animateDialog = setTimeout(animate, 2500);
  // set removal from dom timer
  removeDialog = setTimeout(remove, 3000);
});

// enable dismissability of dialog upon click
$(document).on('click', '.dialog', function() {
  // add animation out class
  $('body .dialog').addClass('out');
  // clear timers
  clearTimeout(removeDialog);
  // remove from dom
  removeDialog = setTimeout(remove, 600);
});


// function to add class for animating out
function animate() {
  $('.dialog').addClass('out');
}

// function to remove dialog from dom
function remove() {
  $('.dialog').remove();
}