Kuba
Kuba

Reputation: 2089

Make PrimeFaces messages disappear after 5 seconds

My new task is to have PrimeFaces <p:messages> dissappear after 5 seconds after appearing. I haven't found any specific setting for that in PF's user guide, nor on their webpage. I thought maybe I could bind an JavaScript event to <p:messages> appearing, but don't know where to start.

My messages are in the Template:

<p:messages id="messages" globalOnly="true" autoUpdate="true" closable="true" rendered="#{not suppressMessages}" />

and render such an empty <div> in DOM:

<div id="messages" class="ui-messages ui-widget" aria-live="polite"></div>

and full:

<div id="messages" class="ui-messages ui-widget" aria-live="polite">
  <div class="ui-messages-info ui-corner-all">
   <a class="ui-messages-close" onclick="$(this).parent().slideUp();return false;" href="#">
   <span class="ui-messages-info-icon"></span>
    <ul>
      <li>
       <span class="ui-messages-info-summary">Sample info message</span>
      </li>
    </ul>
  </div>
</div>

Does anyone know of a jQuery or Primefaces specific solution?

Solution

I've found the combination of jQuery and <p:ajaxStatus> to be the solution to my problem. I've added:

<p:ajaxStatus onstart="PF('statusDialog').show()" onsuccess="setTimeout(function() { $('.ui-messages').slideUp(); }, 5000); PF('statusDialog').hide();" />

to my <p:ajaxStatus> and some jQuery in case of non ajax messages.

jQuery(document).ready(function() { 
    if(!$.trim($(".ui-messages").html())==''){
       //console.log("messages found");
       setTimeout(function() {$('.ui-messages').slideUp();}, 5000);
   } else {
       //console.log("messages not found");
   }    
});

Thanks for the lead BalusC!

Upvotes: 5

Views: 7104

Answers (1)

BalusC
BalusC

Reputation: 1108912

You can use <p:ajaxStatus> to hook on ajax start, complete, success and error events. You can then just fire a setTimeout() on a slideUp() of the messages.

<p:ajaxStatus oncomplete="setTimeout(function() { $('.ui-messages').slideUp(); }, 5000)" />

Or, more generically, you could also use jQuery's $.ajaxStop() for this.

$(document).ajaxStop(function() {
    setTimeout(function() {
        $('.ui-messages').slideUp();
    }, 5000);
});

Upvotes: 3

Related Questions