Skip to content

Instantly share code, notes, and snippets.

@adactio

adactio/giveFeedback.js

Last active Dec 8, 2020
Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@adactio adactio commented Sep 30, 2020

@adactio

This comment has been minimized.

Copy link
Owner Author

@adactio adactio commented Sep 30, 2020

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