noticer/noticer.js

103 lines
2.7 KiB
JavaScript
Raw Permalink Normal View History

/*! noticer - v0.1.1 - 2023-06-02
* https://git.zhirov.kz/alexander/noticer
* Copyright Alexander Zhirov; Licensed GPL-2.0 */
class Noticer {
constructor() {
this.div = $('<div id="noticer"></div>');
this.div.css({
"position": "absolute",
"top": "10px",
"right": "20px",
"z-index": "1000"
});
$('body').append(this.div);
}
success(message, delay = 6000) {
this.print(message, delay, '#52b818', '#bffdc0');
}
warning(message, delay = 6000) {
this.print(message, delay, '#b8ae18', '#f8fdbf');
}
error(message, delay = 6000) {
this.print(message, delay, '#b96161', '#fddede');
}
print = function(message, delay, border, background) {
if (delay < 6000) delay = 6000;
let Timer = function(callback, delay) {
let timerId, start, remaining = delay;
this.pause = function() {
clearTimeout(timerId);
remaining -= new Date() - start;
};
this.resume = function() {
start = new Date();
clearTimeout(timerId);
timerId = setTimeout(callback, remaining);
};
this.dead = function() {
clearTimeout(timerId);
};
this.resume();
}
let newNotice = $(`<div class="notice">${message}</div>`);
newNotice.css({
"border": `1px solid ${border}`,
"background-color": `${background}`,
"color": "#333",
"padding": "10px 30px",
"text-align": "center",
"display": "none",
"margin": "10px 0 0 0",
"width": "350px",
"opacity": "1",
"cursor": "pointer"
});
newNotice.hover(function(){
$(this).css({
"opacity": "1"
});
}, function(){
$(this).css({
"opacity": "0.3"
});
});
this.div.append(newNotice);
let opacityTimeout = setTimeout(function() {
newNotice.fadeTo(1000, 0.3);
}, 2500);
newNotice.fadeIn(500).mouseenter(() => {
clearTimeout(opacityTimeout);
timer.pause();
}).mouseleave(() => {
timer.resume();
}).click(() => {
timer.dead();
newNotice.fadeOut(0, function(){
this.remove();
});
});
let timer = new Timer(() => {
newNotice.fadeOut(500, function(){
this.remove();
});
}, delay);
}
}