Skip to content

Instantly share code, notes, and snippets.

@adactio
Last active August 27, 2022 11:22
Show Gist options
  • Save adactio/44e2fb4faadf513b3c07e57f5fd954fb to your computer and use it in GitHub Desktop.
Save adactio/44e2fb4faadf513b3c07e57f5fd954fb to your computer and use it in GitHub Desktop.
An unobtrusive animation effect for providing feedback to the user.
// Licensed under a CC0 1.0 Universal (CC0 1.0) Public Domain Dedication
// http://creativecommons.org/publicdomain/zero/1.0/
/*
This function takes two arguments:
element: a reference to a DOM node in the document e.g. a button.
feedbackContent: a string of text or HTML.
An example of usage would be:
document.querySelector('button').addEventListener('click', function() {
giveFeedback(this, 'Wheee!');
});
*/
function giveFeedback(element, feedbackContent) {
var feedback = document.createElement('span');
feedback.setAttribute('role', 'status');
feedback.innerHTML = feedbackContent;
document.querySelector('body').appendChild(feedback);
var elementBox = element.getBoundingClientRect();
var feedbackBox = feedback.getBoundingClientRect();
var y = Math.round((elementBox.top + window.scrollY) - feedbackBox.height);
var x = Math.round((elementBox.left + window.scrollX + (elementBox.width/2)) - (feedbackBox.width/2));
feedback.style.position = 'absolute';
feedback.style.left = x + 'px';
feedback.style.top = y + 'px';
feedback.style.opacity = 1;
feedback.style.transition = 'transform 1s, opacity 1s';
feedback.style.transform = 'translateY(-75px)';
feedback.style.opacity = 0;
feedback.addEventListener('transitionend', function () {
if (feedback.parentNode) {
feedback.parentNode.removeChild(feedback);
}
}, false);
}
@adactio
Copy link
Author

adactio commented Sep 30, 2020

@adactio
Copy link
Author

adactio commented Sep 30, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment