A simple jQuery plugin for temporarily displaying any DOM element
So before I get started, I’m sure there are a lot of these plugins floating around, I haven’t bothered to look for one as I wanted to write one from scratch (just for the sport of it
).
My initial goal was to display a temporary “Your data has been saved” message, once a specific interval has been reached, the element would go away. Quickly seeing an opportunity to make this work on a universal level (displaying any element in the DOM temporarily), I decided to write this simple plugin:
(function($) {
$.fn.tempDisplay.defaults = {
delay: 3000
};
$.fn.tempDisplay = function (options) {
var settings = $.extend({ }, $.fn.tempDisplay.defaults, options);
this.each(function () {
var $this = $(this);
$this.show("fast");
setTimeout(function () {
$this.hide("slow");
}, settings.delay);
});
return this;
};
})(jQuery)
One thing to note about this if you’re not familiar with jQuery plugins, this must come after the jquery include on your page, otherwise the objects do not exist
As you can see, there isn’t much to it. I have created one option which is the interval the element should delay hiding itself. There are other options I might want to play with here like the show/hide speed, and the show/hide effect, however, this works for my needs at the moment.
Once you have declared this plugin, you can simply use it like so:
$(function () { $(".temp-message").tempDisplay({ delay: 5000 }); });
Remember, this will only work if you register the elements in the page load, as is the case in the above code snippet.
I have only used it for one scenario, and I can envision many more, I may update it if I feel frisky enough to extend the code. Feel free to copy this code and use it to your hearts desire. Hope it helps give someone a leg up on their project!