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

Time for action – displaying notification messages

Let us see how to create a simple notification bar to display a message using JavaScript show() and hide() methods.

  1. Create a NotificationBar component to display notification messages and two buttons to show and hide the notification bar widget:
    <p:notificationBar id="bar" widgetVar="notifBar" 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()"/>
    </h:form>

What just happened?

We have created a notification bar widget using a <p:notificationBar> component. When the Show and Hide buttons are clicked, we have displayed and closed NotificationBar using the client-side JavaScript API calls notifBar.show() and notifBar.hide().

By default, NotificationBar is hidden. If you want to display NotificationBar on page load set autoDisplay="true".

You can apply effects while displaying and hiding the NotificationBar using the effect attribute. Default is fade. If you don't want to apply any effects, you can set effect="none" which will turn off the animation effects. Also you can set the speed of effect using the effectSpeed attribute that can take normal, slow or fast as its value:

<p:notificationBar id="bar" widgetVar="notifBar" 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>

By default, NotificationBar will be placed at the top of the page. You can set position="bottom" to display NotificationBar at the bottom of the page. As the NotificationBar positioning is fixed, even if you scroll the page, the notification bar will not scroll.

Hiding NotificationBar automatically

Once the notification bar is displayed, you may want to hide it automatically with a delay. You can do this using the JavaScript setTimeout() method as follows: