wesleyhales.com

Replacing FacesMessages with Growl alerts

10 August 2009

Java | growl | jsf | richfaces |

I saw a tweet from(@maxandersen) the other day and decided to try adding Growl like messages in a standard JSF/Richfaces application using jGrowl. It is quite simple and my approach could definitely be improved upon.

This is really just javascript on the front end and can be used with any backend message generating system.

Code Used:

Include the scripts in the head:

Note the loading of jquery in the Richfaces page...

 
 
 <a4j:loadScript src="resource://jquery.js"/> 
<link rel="stylesheet" href="/css/jquery-plugins/jquery.jgrowl.css" type="text/css"/> 
 <script type="text/javascript" src="/js/jquery-plugins/jquery.jgrowl.js"></script> 
 
  

Write a simple script to extract the message:

... and add any customizations you may need to jGrowl. One thing to take note of here is that you cannot use the $ sign for jQuery in a Richfaces app. This is because of the RF framework using prototype.js by default and it too uses the $ sign. So every 3rd party jQuery script that you use, you must s/$/jQuery/g (find and replace all usages of '$' with 'jQuery')

 
function showError() 
{ 
jQuery.jGrowl.defaults.position = 'center'; 
if (document.getElementById('errorMessage') != null) 
{ 
jQuery.jGrowl(jQuery('#errorMessage').html(), { 
sticky: false, 
life: 10000 
}) 
} 
} 

And tell the script to run after page load:

jQuery has a simple statement that checks the document and waits until it's ready to be manipulated, known as the ready event:

 
$(document).ready(function(){ 
showError(); 
}); 

Here is a live screen shot of the script in action using a generate h:message.