Skip to content

Instantly share code, notes, and snippets.

@ChristianPeters
Created November 17, 2010 12:52
Show Gist options
  • Save ChristianPeters/703357 to your computer and use it in GitHub Desktop.
Save ChristianPeters/703357 to your computer and use it in GitHub Desktop.
This script implements a register of calls in order to have guarded access on a (shared) single dom element. In particular, the flash message div (user notification banner) should only fade out if the last user notification has been displayed for 5-6 secs
// Module that encapsulates access to numberOfCalls and numberOfCompletedCalls.
// Facilitates the ensurance that every flash message is displayed for 5-6 sec.
// Use registerOne() to register a flash message (before calling fade!).
// Use completeOne() once to indicate that a flash message has passed its display time.
// Use allowFade() in order to ask whether the flash div can be faded out now.
Register = function () {
var numberOfCalls = 0;
var numberOfCompletedCalls = 0;
return {
registerOne: function() {
numberOfCalls++;
},
completeOne: function() {
numberOfCompletedCalls++;
},
allowFade: function() {
return (numberOfCalls == numberOfCompletedCalls);
}
};
};
RegisterOfCalls = Register();
// Call guardedFade() in order to ensure that the flash message is displayed for 5-6 sec.
function guardedFade() {
return function() {
RegisterOfCalls.completeOne();
tryFade();
}.delay(5);
}
// tryFade polls for the allowance to fade out the flash div.
function tryFade() {
return function() {
if(RegisterOfCalls.allowFade()) {
Effect.Fade('flash', { duration: 0.5 });
} else {
tryFade();
}
}.delay(1);
}
// displays flash message by replacing the existing flash div
function flash(flash_div) {
RegisterOfCalls.registerOne();
var id = 'flash';
$(id).replace(flash_div);
// TODO schmidt: document this. How does the div get displayed? Is the flash message displayed at all in IE 7.0?
if (navigator.userAgent.indexOf("MSIE 7.0") == -1) {
Effect.Appear(id, { duration: 0.5 });
}
guardedFade();
}
// hides the unobtrusive flash message on page load (if javascript enabled)
// calls the initial flash method
function initial_hide() {
var id = 'flash_unobtrusive';
if($(id)) {
$(id).hide();
// get existing message and interaction class
flashMessage($(id).innerHTML, getInteractionClass(id));
}
}
function flashMessage(message, type) {
// default: type = notice
type = typeof(type) != 'undefined' ? type : 'notice';
var id = 'flash';
// build flash_div and call flash()
flash("<div id='" + id + "' class='" + type + "'>" + message + "</div>");
}
function getInteractionClass(id) {
return $(id).hasClassName('error') ? 'error' : ($(id).hasClassName('success') ? 'success' : 'notice')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment