PrimeFaces Beginner's Guide
上QQ阅读APP看书,第一时间看更新

Time for action – automatically hiding NotificationBar

In this section we will demonstrate how to display the PrimeFaces NotificationBar component and automatically hide it using the JavaScript setTimeout() function.

  1. Create a NotificationBar widget and buttons to show and hide it using the following code:
    <p:notificationBar id="bar" widgetVar="notifBar" position="top" effect="slide" effectSpeed="slow" style="height: 20px; background-color: #8B0000;">
      <h:outputText value="There are New Unread Emails in your MailBox." style="color:#FFF;font-size:20px;"/>
    </p:notificationBar>
    
    <h:form>
      <p:commandButton value="Show" onclick="notifBar.show()"/>
      <p:commandButton value="Hide" onclick="notifBar.hide()"/>  
      <p:commandButton value="Show &amp; Auto Hide" onclick="showNotifBar()"/>  
    </h:form>
  2. Create an onclick event handler JavaScript function showNotifBar() using the following code:
    <script>
      var timeoutID = null;
      function showNotifBar() 
      {
        notifBar.show();
        timeoutID = window.setTimeout(hideNotifBar, 5000);
      }
    
      function hideNotifBar()
      {
        notifBar.hide();
        if(timeoutID != null)
        {
          window.clearTimeout(timeoutID);
        }
      }
    </script>

What just happened?

When the Show & Auto Hide button is clicked, the showNotifBar() function gets invoked and the notification bar is displayed by calling notifBar.show(). Also, we are using the window.setTimeout() function to call hideNotifBar() with a delay of 5000 milliseconds, which will close the notification bar using the notifBar.hide() method.