Ask JW: A Plugin to Make Important Announcements

Today’s Q&A comes courtesy of Frederico Gonzalez, from Twitter. He asked if there was an easy way to add announcement bars to the top of his site, much like the one on ActiveDen right now (assuming you’re not logged in). Luckily, as you’ll find, it’s quite simple to whip up a jQuery plugin that will make these announcements a cinch to add.

The Screencast

The Final Plugin

(function($) {
 
$.fn.jwAnnounce = function(options) {
 
	var options = $.extend({
		className : 'notice',
		text : null,
		siteWidth : null }, options);
 
	return this.each(function() {
		$(this).prepend('<div class="' + options.className + '" />');
 
		var $announceDiv = $('.' + options.className);
 
		$announceDiv
			.append('<div>' + options.text + '</div>')
			.children('div:last')
				.css({
					'width' : options.siteWidth,
					'margin' : 'auto'
				})
			.end()
			.prepend('<span class="close">X</span>')
			.children('.close')
				.css({
					'position' : 'absolute',
					'cursor' : 'pointer',
					'display' : 'none'
				})
			.end()
 
			.hover(function() {
				// over
				$(this)
					.children('.close')
					.show()
					.click(function() {
						$announceDiv.slideUp(250, function() {
							$(this).remove();
						});
					})
			}, function() {
				$('.close').hide();
			});
	}); // end each
 
}
 
})(jQuery);

6

Comments

Discuss This Post on the ThemeForest Forums